Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:cn.zhangls.android.weibo.ui.weibo.RecyclerItemAnimator.java

@Override
public void runPendingAnimations() {
    boolean removalsPending = !mPendingRemovals.isEmpty();
    boolean movesPending = !mPendingMoves.isEmpty();
    boolean changesPending = !mPendingChanges.isEmpty();
    boolean additionsPending = !mPendingAdditions.isEmpty();
    if (!removalsPending && !movesPending && !additionsPending && !changesPending) {
        // nothing to animate
        return;//from   w  w  w  . j  a v a  2 s  .com
    }
    // First, remove stuff
    for (RecyclerView.ViewHolder holder : mPendingRemovals) {
        animateRemoveImpl(holder);
    }
    mPendingRemovals.clear();
    // Next, move stuff
    if (movesPending) {
        final ArrayList<MoveInfo> moves = new ArrayList<>();
        moves.addAll(mPendingMoves);
        mMovesList.add(moves);
        mPendingMoves.clear();
        Runnable mover = new Runnable() {
            @Override
            public void run() {
                for (MoveInfo moveInfo : moves) {
                    animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX,
                            moveInfo.toY);
                }
                moves.clear();
                mMovesList.remove(moves);
            }
        };
        if (removalsPending) {
            View view = moves.get(0).holder.itemView;
            ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration());
        } else {
            mover.run();
        }
    }
    // Next, change stuff, to run in parallel with move animations
    if (changesPending) {
        final ArrayList<ChangeInfo> changes = new ArrayList<>();
        changes.addAll(mPendingChanges);
        mChangesList.add(changes);
        mPendingChanges.clear();
        Runnable changer = new Runnable() {
            @Override
            public void run() {
                for (ChangeInfo change : changes) {
                    animateChangeImpl(change);
                }
                changes.clear();
                mChangesList.remove(changes);
            }
        };
        if (removalsPending) {
            RecyclerView.ViewHolder holder = changes.get(0).oldHolder;
            ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration());
        } else {
            changer.run();
        }
    }
    // Next, add stuff
    if (additionsPending) {
        final ArrayList<RecyclerView.ViewHolder> additions = new ArrayList<>();
        additions.addAll(mPendingAdditions);
        mAdditionsList.add(additions);
        mPendingAdditions.clear();
        Runnable adder = new Runnable() {
            @Override
            public void run() {
                for (RecyclerView.ViewHolder holder : additions) {
                    animateAddImpl(holder);
                }
                additions.clear();
                mAdditionsList.remove(additions);
            }
        };
        if (removalsPending || movesPending || changesPending) {
            long removeDuration = removalsPending ? getRemoveDuration() : 0;
            long moveDuration = movesPending ? getMoveDuration() : 0;
            long changeDuration = changesPending ? getChangeDuration() : 0;
            long totalDelay = removeDuration + Math.max(moveDuration, changeDuration);
            View view = additions.get(0).itemView;
            ViewCompat.postOnAnimationDelayed(view, adder, totalDelay);
        } else {
            adder.run();
        }
    }
}

From source file:sim.app.sugarscape.Sugarscape.java

public void start() {
    super.start();
    agents_grid.clear();/*from w w  w .  ja v  a  2 s  . c  o m*/
    scape_grid.clear();
    //scape_grid = new ObjectGrid2D(gridWidth, gridHeight);
    sim.app.sugarscape.Agent agent;
    /* If the season rate is very large, it will be summer for all foreseable simulation runs in the north and winter
    in the south. Growback rates for each are set as parameters and normally default to 1 */
    north_season = SUMMER;
    south_season = WINTER;
    Steppable season_changer = new Steppable() {
        public void step(SimState state) {
            Sugarscape sugar = (Sugarscape) state;
            if (sugar.north_season == SUMMER) {
                sugar.north_season = WINTER;
                sugar.south_season = SUMMER;
            } else {
                sugar.north_season = SUMMER;
                sugar.south_season = WINTER;
            }
        }
    };

    MultiStep season_multi = new MultiStep(season_changer, season_rate, true);
    schedule.scheduleRepeating(Schedule.EPOCH, 3, season_multi, 1); //change seasons last in order

    if (agents_file != null) { //config file for setting up agents spatial config
        try {
            InputStream is = Class.forName(sim.app.sugarscape.Sugarscape.class.getCanonicalName())
                    .getClassLoader().getResourceAsStream(agents_file);
            InputStreamReader ir = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(ir);

            String line = br.readLine();
            int y = 0;
            int affiliation;
            String affil_code;
            while (line != null) {
                int x = 0;
                int size = line.length();
                while (x < size) {
                    affil_code = line.substring(x, x + 1);
                    affiliation = Integer.parseInt(affil_code);
                    if (affiliation != 0) {
                        agent = this.newAgent();
                        agents_grid.field[x][y] = agent; //,new Int2D(x,y));
                        agent.my_loc.x = x;
                        agent.my_loc.y = y;
                    }
                    x++;
                }
                line = br.readLine();
                y++;
                //System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else { //otherwise distribute randomly in space
        for (int a = 0; a < numAgents; a++) {
            createNewAgent();
        }
    }

    ArrayList rows = new ArrayList(50);
    for (int a = 0; a < resources; a++) {
        rows.clear();
        try {
            InputStream is = Class.forName(sim.app.sugarscape.Sugarscape.class.getCanonicalName())
                    .getClassLoader().getResourceAsStream(terrain_files[a]);
            InputStreamReader ir = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(ir);
            String line = br.readLine();
            while (line != null) {
                rows.add(line);
                line = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int row_count = rows.size();
        int capacity;
        String max;
        int equator = row_count / 2;
        int hemisphere = NORTH;
        Object[][] all_objs = scape_grid.field;
        //Object[][] all_pollut = pollution_grid.field;
        for (int y = 0; y < gridHeight; y++) {
            if (y >= equator) {
                hemisphere = SOUTH;
            }
            StringBuffer sb = new StringBuffer((String) rows.get(y));
            int type;
            for (int x = 0; x < gridWidth; x++) {
                max = sb.substring(x, x + 1);
                capacity = Integer.parseInt(max);
                if (capacity > 4) { //terrain file has values of 0-4, and 0,5-8
                    type = SPICE;
                    capacity = capacity - 4;
                } else {
                    type = SUGAR;
                }
                if (all_objs[x][y] == null) {
                    Scape site = new Scape(x, y, hemisphere, pollution_diffusion, this);
                    site.setResource(type, capacity, 1,
                            capacity); /* idealy the growback rate, third param, should not be constant */
                    all_objs[x][y] = site;
                } else {
                    ((Scape) all_objs[x][y]).setResource(type, capacity, 1, capacity);
                }
            }
        }
    }
    this.initializeEnvironment();

    //set up charts
    avg_agent_vision.clear();
    lorenz_curve.clear();
    gini_coeff.clear();
    agents_series.clear();
    blue_agents.clear();
    red_agents.clear();
    trade_series.clear();

    if (stats_rate > 0) {
        Statistics stats = new Statistics(this, schedule, stats_out);
        MultiStep multi_lorenz = new MultiStep(stats, stats_rate, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 4, multi_lorenz, 1);
        stats.step(this);
    }
    //calculate and output frequency count for metabolic 'bins'
    //that is the total metabolism for each each across the population
    Steppable metabolism_bins_updater = new Steppable() {
        Histogram h = new Histogram("Metabolism", "Vision", 1 + metabolic_sugar + metabolic_spice, 5);

        public void step(SimState state) {
            //agents_grid.

            Bag all = null; //agents_grid.getAllObjects();
            int size = all.size();
            int total = 0;
            Object[] all_obj = all.objs;
            h.zero();
            for (int a = 0; a < size; a++) {
                Agent ag = (Agent) all_obj[a];
                total = ag.metabolic_rate_spice + ag.metabolic_rate_sugar;
                h.bins[total] = h.bins[total] + 1;
                h.bins_assoc[total] = h.bins_assoc[total] + ag.vision;
            }
            h.render();
            System.out.println(size + " = size, " + (state.schedule.time() + 1) + " = steps.");

        }
    };

    if (print_metabolism_bins) {
        MultiStep multi_metabolism_bins = new MultiStep(metabolism_bins_updater, metabolism_bins_freq, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 6, multi_metabolism_bins, 1);
        multi_metabolism_bins.step(this);
    }

    //TO DO: Restore this
    if (logger != null) {
        MultiStep multi_logger = null; //new MultiStep(logger, log_frequency, true);
        //use order 4 along with statistics steppable
        //System.out.println("Logging "+ logger.grids.size() + " grids.");
        schedule.scheduleRepeating(Schedule.EPOCH, 4, multi_logger, 1);
        //Thread t = new Thread(logger);
        //t.start();
    }

    Steppable chart_updater = new Steppable() {
        private static final int BINS = 10;
        private float total;
        private float wealth_sugar_total;
        private double[] ages;

        public void step(SimState state) {

            Bag all = null; //agents_grid.getAllObjects();
            int size = active_agents_count;
            double[] values = null;
            if (size != 0) { /* what if there are zero agents? */
                values = new double[size];
            } else {
                values = new double[1];
                values[0] = 0;
            }
            total = 0;
            wealth_sugar_total = 0;
            if (age_chart_on) {
                ages = new double[size];
            }
            Iterator<Agent> i = active_agents.iterator();
            int a = 0;
            while (i.hasNext()) {
                Agent agent = i.next();
                values[a] = agent.wealth_sugar;
                wealth_sugar_total = wealth_sugar_total + agent.wealth_sugar;
                if (age_chart_on) {
                    ages[a] = agent.age;
                }
                a++;
            }

            if (age_chart_on) {
                age_hist_dataset = new HistogramDataset();
                age_hist_dataset.addSeries(Double.toString(state.schedule.time()), ages, 10);
                XYPlot xy = ((Sugarscape) state).age_histo_chart.getXYPlot();
                xy.setDataset(age_hist_dataset);
            }

            if (wealth_chart_on) {
                dataset = new HistogramDataset();
                dataset.addSeries(Double.toString(state.schedule.time()), values, 10);
                XYPlot xy = ((Sugarscape) state).chart4.getXYPlot();
                xy.setDataset(dataset);
                XYItemRenderer r = xy.getRenderer();
                XYItemLabelGenerator xylg = new StandardXYItemLabelGenerator("{2}", new DecimalFormat("0.00"),
                        new DecimalFormat("0.00"));
                r.setItemLabelGenerator(xylg);
                r.setItemLabelsVisible(true);
            }
        }
    };
    // Schedule the agent to update the chart
    if (chart_display) {
        MultiStep multi_chart = new MultiStep(chart_updater, chart_rate, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 6, multi_chart, 1);
        chart_updater.step(this);
    }
}

From source file:accumulo.balancer.GroupBalancer.java

private void balanceExtraExpected(Map<TServerInstance, TserverGroupInfo> tservers, int expectedExtra,
        Moves moves) {/*ww w . j a  v a2 s . c o  m*/

    Table<String, TServerInstance, TserverGroupInfo> extraSurplus = HashBasedTable.create();

    for (TserverGroupInfo tgi : tservers.values()) {
        Map<String, Integer> extras = tgi.getExtras();
        if (extras.size() > expectedExtra) {
            for (String group : extras.keySet()) {
                extraSurplus.put(group, tgi.getTserverInstance(), tgi);
            }
        }
    }

    ArrayList<TServerInstance> emptyServers = new ArrayList<>();
    ArrayList<Pair<String, TServerInstance>> emptyServerGroups = new ArrayList<>();
    for (TserverGroupInfo destTgi : tservers.values()) {
        if (extraSurplus.size() == 0) {
            break;
        }

        Map<String, Integer> extras = destTgi.getExtras();
        if (extras.size() < expectedExtra) {
            emptyServers.clear();
            emptyServerGroups.clear();
            nextGroup: for (String group : extraSurplus.rowKeySet()) {
                if (!extras.containsKey(group)) {
                    Iterator<TserverGroupInfo> iter = extraSurplus.row(group).values().iterator();
                    TserverGroupInfo srcTgi = iter.next();

                    while (srcTgi.getExtras().size() <= expectedExtra) {
                        if (iter.hasNext()) {
                            srcTgi = iter.next();
                        } else {
                            continue nextGroup;
                        }
                    }

                    moves.move(group, 1, srcTgi, destTgi);

                    if (srcTgi.getExtras().size() <= expectedExtra) {
                        emptyServers.add(srcTgi.getTserverInstance());
                    } else if (srcTgi.getExtras().get(group) == null) {
                        emptyServerGroups
                                .add(new Pair<String, TServerInstance>(group, srcTgi.getTserverInstance()));
                    }

                    if (destTgi.getExtras().size() >= expectedExtra || moves.size() >= getMaxMigrations()) {
                        break;
                    }
                }
            }

            if (emptyServers.size() > 0) {
                extraSurplus.columnKeySet().removeAll(emptyServers);
            }

            for (Pair<String, TServerInstance> pair : emptyServerGroups) {
                extraSurplus.remove(pair.getFirst(), pair.getSecond());
            }

            if (moves.size() >= getMaxMigrations()) {
                break;
            }
        }
    }
}

From source file:eu.davidea.samples.anim.BaseItemAnimator.java

@Override
public void runPendingAnimations() {
    boolean removalsPending = !mPendingRemovals.isEmpty();
    boolean movesPending = !mPendingMoves.isEmpty();
    boolean changesPending = !mPendingChanges.isEmpty();
    boolean additionsPending = !mPendingAdditions.isEmpty();
    if (!removalsPending && !movesPending && !additionsPending && !changesPending) {
        // nothing to animate
        return;/*from  w  w w  . ja  va 2s.c om*/
    }
    // First, remove stuff
    for (ViewHolder holder : mPendingRemovals) {
        doAnimateRemove(holder);
    }
    mPendingRemovals.clear();
    // Next, move stuff
    if (movesPending) {
        final ArrayList<MoveInfo> moves = new ArrayList<>();
        moves.addAll(mPendingMoves);
        mMovesList.add(moves);
        mPendingMoves.clear();
        Runnable mover = new Runnable() {
            @Override
            public void run() {
                for (MoveInfo moveInfo : moves) {
                    animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX,
                            moveInfo.toY);
                }
                moves.clear();
                mMovesList.remove(moves);
            }
        };
        if (removalsPending) {
            View view = moves.get(0).holder.itemView;
            ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration());
        } else {
            mover.run();
        }
    }
    // Next, change stuff, to run in parallel with move animations
    if (changesPending) {
        final ArrayList<ChangeInfo> changes = new ArrayList<>();
        changes.addAll(mPendingChanges);
        mChangesList.add(changes);
        mPendingChanges.clear();
        Runnable changer = new Runnable() {
            @Override
            public void run() {
                for (ChangeInfo change : changes) {
                    animateChangeImpl(change);
                }
                changes.clear();
                mChangesList.remove(changes);
            }
        };
        if (removalsPending) {
            ViewHolder holder = changes.get(0).oldHolder;
            ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration());
        } else {
            changer.run();
        }
    }
    // Next, add stuff
    if (additionsPending) {
        final ArrayList<ViewHolder> additions = new ArrayList<>();
        additions.addAll(mPendingAdditions);
        mAdditionsList.add(additions);
        mPendingAdditions.clear();
        Runnable adder = new Runnable() {
            public void run() {
                for (ViewHolder holder : additions) {
                    doAnimateAdd(holder);
                }
                additions.clear();
                mAdditionsList.remove(additions);
            }
        };
        if (removalsPending || movesPending || changesPending) {
            long removeDuration = removalsPending ? getRemoveDuration() : 0;
            long moveDuration = movesPending ? getMoveDuration() : 0;
            long changeDuration = changesPending ? getChangeDuration() : 0;
            long totalDelay = removeDuration + Math.max(moveDuration, changeDuration);
            View view = additions.get(0).itemView;
            ViewCompat.postOnAnimationDelayed(view, adder, totalDelay);
        } else {
            adder.run();
        }
    }
}

From source file:de.helmholtz_muenchen.ibis.ngs.mats.MatsNodeModel.java

@Override
protected LinkedHashMap<String, String> getGUIParameters(final BufferedDataTable[] inData) {
    LinkedHashMap<String, String> pars = new LinkedHashMap<String, String>();

    /********************* SIMPLE PARAMETER ***************************/
    if (SET_ANALYSIS_TYPE.getBooleanValue())
        pars.put(NAME_OF_PAIRED_ANALYSIS, "P");
    else/*from  w  w  w.jav  a  2 s  .  c  o m*/
        pars.put(NAME_OF_PAIRED_ANALYSIS, "U");
    if (SET_READ_LENGTH.getIntValue() > 1)
        pars.put(NAME_OF_READ_LENGTH, Integer.toString(SET_READ_LENGTH.getIntValue()));

    pars.put(NAME_OF_ANNOTATION_FILE, SET_ANNOTATION_FILE.getStringValue());
    pars.put(NAME_OF_CUTOFF_DIFFERENCE,
            Double.toString(Math.min(SET_CUTOFF_DIFFERENCE.getDoubleValue(), VALID_FOLDCHANGE_CUTOFF)));
    pars.put(NAME_OF_EXPRESSION_CHANGE, Double.toString(SET_EXPRESSION_CHANGE.getDoubleValue()));

    /********************* OUTPUT ****************************/
    String outputFolderArgument = SET_OUTPUT_FOLDER.getStringValue();
    File outDir = new File(outputFolderArgument).getParentFile();
    // create folder, if not already there
    if (!outDir.isDirectory())
        outDir.mkdir();

    pars.put(NAME_OF_OUTPUT_FOLDER, outputFolderArgument);

    /********************** INPUT BAM SETTINGS OF CONDITION 1 ****************************/
    ArrayList<String> bamArgument = new ArrayList<String>();
    ArrayList<String> insertArgument = new ArrayList<String>();
    ArrayList<String> standardDevArgument = new ArrayList<String>();

    // get input parameter from BAM/SAM selector
    for (Iterator<DataRow> it = inData[0].iterator(); it.hasNext();) {
        DataRow row = it.next();
        bamArgument.add(row.getCell(0).toString());
        insertArgument.add(row.getCell(1).toString());
        standardDevArgument.add(row.getCell(2).toString());
    }

    // add the input parameter
    pars.put(NAME_OF_BAM1, StringUtils.join(bamArgument, ","));
    pars.put(NAME_OF_INSERT_SIZE1, StringUtils.join(insertArgument, ","));
    pars.put(NAME_OF_STANDARD_DEV1, StringUtils.join(standardDevArgument, ","));

    /********************** INPUT BAM SETTINGS OF CONDITION 1 ****************************/
    bamArgument.clear();
    insertArgument.clear();
    standardDevArgument.clear();

    // get input parameter from BAM/SAM selector
    for (Iterator<DataRow> it = inData[1].iterator(); it.hasNext();) {
        DataRow row = it.next();
        bamArgument.add(row.getCell(0).toString());
        insertArgument.add(row.getCell(1).toString());
        standardDevArgument.add(row.getCell(2).toString());
    }

    // add the input parameter
    pars.put(NAME_OF_BAM2, StringUtils.join(bamArgument, ","));
    pars.put(NAME_OF_INSERT_SIZE2, StringUtils.join(insertArgument, ","));
    pars.put(NAME_OF_STANDARD_DEV2, StringUtils.join(standardDevArgument, ","));

    // return the GUI parameter
    return pars;
}

From source file:org.apache.ddlutils.io.DataToDatabaseSink.java

/**
 * {@inheritDoc}//  w w  w  .jav a2 s. co  m
 */
public void addBean(DynaBean bean) throws DataSinkException {
    Table table = _model.getDynaClassFor(bean).getTable();
    Identity origIdentity = buildIdentityFromPKs(table, bean);

    if (_ensureFkOrder && (table.getForeignKeyCount() > 0)) {
        WaitingObject waitingObj = new WaitingObject(bean, origIdentity);

        for (int idx = 0; idx < table.getForeignKeyCount(); idx++) {
            ForeignKey fk = table.getForeignKey(idx);
            Identity fkIdentity = buildIdentityFromFK(table, fk, bean);

            if ((fkIdentity != null) && !fkIdentity.equals(origIdentity)) {
                Identity processedIdentity = (Identity) _identityMap.get(fkIdentity);

                if (processedIdentity != null) {
                    updateFKColumns(bean, fkIdentity.getForeignKeyName(), processedIdentity);
                } else {
                    waitingObj.addPendingFK(fkIdentity);
                }
            }
        }
        if (waitingObj.hasPendingFKs()) {
            if (_log.isDebugEnabled()) {
                StringBuffer msg = new StringBuffer();

                msg.append("Defering insertion of row ");
                msg.append(buildIdentityFromPKs(table, bean).toString());
                msg.append(" because it is waiting for:");
                for (Iterator it = waitingObj.getPendingFKs(); it.hasNext();) {
                    msg.append("\n  ");
                    msg.append(it.next().toString());
                }
                _log.debug(msg.toString());
            }
            _waitingObjects.add(waitingObj);
            return;
        }
    }

    insertBeanIntoDatabase(table, bean);

    if (_log.isDebugEnabled()) {
        _log.debug("Inserted bean " + origIdentity);
    }

    if (_ensureFkOrder && _fkTables.contains(table)) {
        Identity newIdentity = buildIdentityFromPKs(table, bean);
        ArrayList finishedObjs = new ArrayList();

        _identityMap.put(origIdentity, newIdentity);

        // we're doing multiple passes so that we can insert as much objects in
        // one go as possible
        ArrayList identitiesToCheck = new ArrayList();

        identitiesToCheck.add(origIdentity);
        while (!identitiesToCheck.isEmpty() && !_waitingObjects.isEmpty()) {
            Identity curIdentity = (Identity) identitiesToCheck.get(0);
            Identity curNewIdentity = (Identity) _identityMap.get(curIdentity);

            identitiesToCheck.remove(0);
            finishedObjs.clear();
            for (Iterator waitingObjIt = _waitingObjects.iterator(); waitingObjIt.hasNext();) {
                WaitingObject waitingObj = (WaitingObject) waitingObjIt.next();
                Identity fkIdentity = waitingObj.removePendingFK(curIdentity);

                if (fkIdentity != null) {
                    updateFKColumns(waitingObj.getObject(), fkIdentity.getForeignKeyName(), curNewIdentity);
                }
                if (!waitingObj.hasPendingFKs()) {
                    waitingObjIt.remove();
                    // we defer handling of the finished objects to avoid concurrent modification exceptions
                    finishedObjs.add(waitingObj.getObject());
                }
            }
            for (Iterator finishedObjIt = finishedObjs.iterator(); finishedObjIt.hasNext();) {
                DynaBean finishedObj = (DynaBean) finishedObjIt.next();
                Table tableForObj = _model.getDynaClassFor(finishedObj).getTable();
                Identity objIdentity = buildIdentityFromPKs(tableForObj, finishedObj);

                insertBeanIntoDatabase(tableForObj, finishedObj);

                Identity newObjIdentity = buildIdentityFromPKs(tableForObj, finishedObj);

                _identityMap.put(objIdentity, newObjIdentity);
                identitiesToCheck.add(objIdentity);
                if (_log.isDebugEnabled()) {
                    _log.debug("Inserted deferred row " + objIdentity);
                }
            }
        }
    }
}

From source file:edu.uci.ics.asterix.optimizer.rules.am.AbstractIntroduceAccessMethodRule.java

/**
 * Removes irrelevant access methods candidates, based on whether the
 * expressions in the query match those in the index. For example, some
 * index may require all its expressions to be matched, and some indexes may
 * only require a match on a prefix of fields to be applicable. This methods
 * removes all index candidates indexExprs that are definitely not
 * applicable according to the expressions involved.
 *
 * @throws AlgebricksException//from ww  w. ja v  a2  s. c o m
 */
public void pruneIndexCandidates(IAccessMethod accessMethod, AccessMethodAnalysisContext analysisCtx)
        throws AlgebricksException {
    Iterator<Map.Entry<Index, List<Pair<Integer, Integer>>>> indexExprAndVarIt = analysisCtx.indexExprsAndVars
            .entrySet().iterator();
    // Used to keep track of matched expressions (added for prefix search)
    int numMatchedKeys = 0;
    ArrayList<Integer> matchedExpressions = new ArrayList<Integer>();
    while (indexExprAndVarIt.hasNext()) {
        Map.Entry<Index, List<Pair<Integer, Integer>>> indexExprAndVarEntry = indexExprAndVarIt.next();
        Index index = indexExprAndVarEntry.getKey();
        boolean allUsed = true;
        int lastFieldMatched = -1;
        boolean foundKeyField = false;
        matchedExpressions.clear();
        numMatchedKeys = 0;
        for (int i = 0; i < index.getKeyFieldNames().size(); i++) {
            List<String> keyField = index.getKeyFieldNames().get(i);
            final IAType keyType = index.getKeyFieldTypes().get(i);
            Iterator<Pair<Integer, Integer>> exprsAndVarIter = indexExprAndVarEntry.getValue().iterator();
            while (exprsAndVarIter.hasNext()) {
                final Pair<Integer, Integer> exprAndVarIdx = exprsAndVarIter.next();
                final IOptimizableFuncExpr optFuncExpr = analysisCtx.matchedFuncExprs.get(exprAndVarIdx.first);
                // If expr is not optimizable by concrete index then remove
                // expr and continue.
                if (!accessMethod.exprIsOptimizable(index, optFuncExpr)) {
                    exprsAndVarIter.remove();
                    continue;
                }
                boolean typeMatch = true;
                //Prune indexes based on field types
                List<IAType> indexedTypes = new ArrayList<IAType>();
                //retrieve types of expressions joined/selected with an indexed field
                for (int j = 0; j < optFuncExpr.getNumLogicalVars(); j++)
                    if (j != exprAndVarIdx.second)
                        indexedTypes.add(optFuncExpr.getFieldType(j));
                //add constants in case of select
                if (indexedTypes.size() < 2 && optFuncExpr.getNumLogicalVars() == 1) {
                    indexedTypes.add((IAType) AqlExpressionTypeComputer.INSTANCE
                            .getType(new ConstantExpression(optFuncExpr.getConstantVal(0)), null, null));
                }
                //infer type of logicalExpr based on index keyType
                indexedTypes.add((IAType) AqlExpressionTypeComputer.INSTANCE.getType(
                        optFuncExpr.getLogicalExpr(exprAndVarIdx.second), null, new IVariableTypeEnvironment() {

                            @Override
                            public Object getVarType(LogicalVariable var) throws AlgebricksException {
                                if (var.equals(optFuncExpr.getSourceVar(exprAndVarIdx.second)))
                                    return keyType;
                                throw new IllegalArgumentException();
                            }

                            @Override
                            public Object getVarType(LogicalVariable var,
                                    List<LogicalVariable> nonNullVariables,
                                    List<List<LogicalVariable>> correlatedNullableVariableLists)
                                    throws AlgebricksException {
                                if (var.equals(optFuncExpr.getSourceVar(exprAndVarIdx.second)))
                                    return keyType;
                                throw new IllegalArgumentException();
                            }

                            @Override
                            public void setVarType(LogicalVariable var, Object type) {
                                throw new IllegalArgumentException();
                            }

                            @Override
                            public Object getType(ILogicalExpression expr) throws AlgebricksException {
                                return AqlExpressionTypeComputer.INSTANCE.getType(expr, null, this);
                            }

                            @Override
                            public boolean substituteProducedVariable(LogicalVariable v1, LogicalVariable v2)
                                    throws AlgebricksException {
                                throw new IllegalArgumentException();
                            }
                        }));

                //for the case when jaccard similarity is measured between ordered & unordered lists
                boolean jaccardSimilarity = optFuncExpr.getFuncExpr().getFunctionIdentifier().getName()
                        .startsWith("similarity-jaccard-check");

                for (int j = 0; j < indexedTypes.size(); j++)
                    for (int k = j + 1; k < indexedTypes.size(); k++)
                        typeMatch &= isMatched(indexedTypes.get(j), indexedTypes.get(k), jaccardSimilarity);

                // Check if any field name in the optFuncExpr matches.
                if (optFuncExpr.findFieldName(keyField) != -1) {
                    foundKeyField = typeMatch
                            && optFuncExpr.getOperatorSubTree(exprAndVarIdx.second).hasDataSourceScan();
                    if (foundKeyField) {
                        matchedExpressions.add(exprAndVarIdx.first);
                        numMatchedKeys++;
                        if (lastFieldMatched == i - 1) {
                            lastFieldMatched = i;
                        }
                        break;
                    }
                }
            }
            if (!foundKeyField) {
                allUsed = false;
                // if any expression was matched, remove the non-matched expressions, otherwise the index is unusable
                if (lastFieldMatched >= 0) {
                    exprsAndVarIter = indexExprAndVarEntry.getValue().iterator();
                    while (exprsAndVarIter.hasNext()) {
                        if (!matchedExpressions.contains(exprsAndVarIter.next().first)) {
                            exprsAndVarIter.remove();
                        }
                    }
                }
                break;
            }
        }
        // If the access method requires all exprs to be matched but they
        // are not, remove this candidate.
        if (!allUsed && accessMethod.matchAllIndexExprs()) {
            indexExprAndVarIt.remove();
            continue;
        }
        // A prefix of the index exprs may have been matched.
        if (accessMethod.matchPrefixIndexExprs()) {
            // Remove the candidate if the dataset is a metadata dataset and the index is secondary
            if (index.getDataverseName().equals(MetadataConstants.METADATA_DATAVERSE_NAME)
                    && !index.isPrimaryIndex()) {
                indexExprAndVarIt.remove();
                continue;
            }
            if (lastFieldMatched < 0) {
                indexExprAndVarIt.remove();
                continue;
            }
        }
        analysisCtx.indexNumMatchedKeys.put(index, new Integer(numMatchedKeys));
    }
}

From source file:android.room.play.com.nasadaily.animators.BaseItemAnimator.java

@Override
public void runPendingAnimations() {
    boolean removalsPending = !mPendingRemovals.isEmpty();
    boolean movesPending = !mPendingMoves.isEmpty();
    boolean changesPending = !mPendingChanges.isEmpty();
    boolean additionsPending = !mPendingAdditions.isEmpty();
    if (!removalsPending && !movesPending && !additionsPending && !changesPending) {
        // nothing to animate
        return;//from w  w  w .j  a v  a  2 s  . c om
    }
    // First, remove stuff
    for (ViewHolder holder : mPendingRemovals) {
        doAnimateRemove(holder);
    }
    mPendingRemovals.clear();
    // Next, move stuff
    if (movesPending) {
        final ArrayList<MoveInfo> moves = new ArrayList<MoveInfo>();
        moves.addAll(mPendingMoves);
        mMovesList.add(moves);
        mPendingMoves.clear();
        Runnable mover = new Runnable() {
            @Override
            public void run() {
                for (MoveInfo moveInfo : moves) {
                    animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX,
                            moveInfo.toY);
                }
                moves.clear();
                mMovesList.remove(moves);
            }
        };
        if (removalsPending) {
            View view = moves.get(0).holder.itemView;
            ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration());
        } else {
            mover.run();
        }
    }
    // Next, change stuff, to run in parallel with move animations
    if (changesPending) {
        final ArrayList<ChangeInfo> changes = new ArrayList<ChangeInfo>();
        changes.addAll(mPendingChanges);
        mChangesList.add(changes);
        mPendingChanges.clear();
        Runnable changer = new Runnable() {
            @Override
            public void run() {
                for (ChangeInfo change : changes) {
                    animateChangeImpl(change);
                }
                changes.clear();
                mChangesList.remove(changes);
            }
        };
        if (removalsPending) {
            ViewHolder holder = changes.get(0).oldHolder;
            ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration());
        } else {
            changer.run();
        }
    }
    // Next, add stuff
    if (additionsPending) {
        final ArrayList<ViewHolder> additions = new ArrayList<ViewHolder>();
        additions.addAll(mPendingAdditions);
        mAdditionsList.add(additions);
        mPendingAdditions.clear();
        Runnable adder = new Runnable() {
            public void run() {
                for (ViewHolder holder : additions) {
                    doAnimateAdd(holder);
                }
                additions.clear();
                mAdditionsList.remove(additions);
            }
        };
        if (removalsPending || movesPending || changesPending) {
            long removeDuration = removalsPending ? getRemoveDuration() : 0;
            long moveDuration = movesPending ? getMoveDuration() : 0;
            long changeDuration = changesPending ? getChangeDuration() : 0;
            long totalDelay = removeDuration + Math.max(moveDuration, changeDuration);
            View view = additions.get(0).itemView;
            ViewCompat.postOnAnimationDelayed(view, adder, totalDelay);
        } else {
            adder.run();
        }
    }
}

From source file:com.example.administrator.bobomanhua.decoration.MyItemAnimator.java

@Override
public void runPendingAnimations() {
    boolean removalsPending = !mPendingRemovals.isEmpty();
    boolean movesPending = !mPendingMoves.isEmpty();
    boolean changesPending = !mPendingChanges.isEmpty();
    boolean additionsPending = !mPendingAdditions.isEmpty();
    if (!removalsPending && !movesPending && !additionsPending && !changesPending) {
        // nothing to animate
        return;/*from  w w  w  .j  av a  2 s. co m*/
    }
    // First, remove stuff
    Collections.sort(mPendingRemovals, new Comparator<ViewHolder>() {
        @Override
        public int compare(ViewHolder lhs, ViewHolder rhs) {
            return rhs.getAdapterPosition() - lhs.getAdapterPosition();
        }
    });
    int i = 0;
    for (ViewHolder holder : mPendingRemovals) {
        animateRemoveImpl(holder, i++);
    }
    mPendingRemovals.clear();
    // Next, move stuff
    if (movesPending) {
        final ArrayList<MoveInfo> moves = new ArrayList<MoveInfo>();
        moves.addAll(mPendingMoves);
        mMovesList.add(moves);
        mPendingMoves.clear();
        Runnable mover = new Runnable() {
            @Override
            public void run() {
                for (MoveInfo moveInfo : moves) {
                    animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX,
                            moveInfo.toY);
                }
                moves.clear();
                mMovesList.remove(moves);
            }
        };
        if (removalsPending) {
            View view = moves.get(0).holder.itemView;
            ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration() + (i - 1) * 100);
        } else {
            mover.run();
        }
    }
    // Next, change stuff, to run in parallel with move animations
    if (changesPending) {
        final ArrayList<ChangeInfo> changes = new ArrayList<ChangeInfo>();
        changes.addAll(mPendingChanges);
        mChangesList.add(changes);
        mPendingChanges.clear();
        Runnable changer = new Runnable() {
            @Override
            public void run() {
                for (ChangeInfo change : changes) {
                    animateChangeImpl(change);
                }
                changes.clear();
                mChangesList.remove(changes);
            }
        };
        if (removalsPending) {
            ViewHolder holder = changes.get(0).oldHolder;
            ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration());
        } else {
            changer.run();
        }
    }
    // Next, add stuff
    if (additionsPending) {
        final ArrayList<ViewHolder> additions = new ArrayList<ViewHolder>();
        additions.addAll(mPendingAdditions);
        mAdditionsList.add(additions);
        mPendingAdditions.clear();
        Runnable adder = new Runnable() {
            public void run() {
                int i = 0;
                Collections.sort(additions, new Comparator<ViewHolder>() {
                    @Override
                    public int compare(ViewHolder lhs, ViewHolder rhs) {
                        return lhs.getAdapterPosition() - rhs.getAdapterPosition();
                    }
                });
                for (ViewHolder holder : additions) {
                    animateAddImpl(holder, i++);
                }
                additions.clear();
                mAdditionsList.remove(additions);
            }
        };
        if (removalsPending || movesPending || changesPending) {
            long removeDuration = removalsPending ? getRemoveDuration() : 0;
            long moveDuration = movesPending ? getMoveDuration() : 0;
            long changeDuration = changesPending ? getChangeDuration() : 0;
            long totalDelay = removeDuration + Math.max(moveDuration, changeDuration);
            View view = additions.get(0).itemView;
            ViewCompat.postOnAnimationDelayed(view, adder, totalDelay);
        } else {
            adder.run();
        }
    }
}

From source file:net.sf.jclal.sampling.supervised.Resample.java

/**
 * creates the subsample with replacement
 *
 * @param dataSet The dataset to extract a percent of instances
 * @param sampleSize the size to generate
 * @param actualClasses The actual classes
 * @param classIndices The indexes of the classes
 *//*  w  w w.j  a  v a  2 s .com*/
public void createSubsampleWithReplacement(WekaDataset dataSet, int sampleSize, int actualClasses,
        int[] classIndices) {

    int originalSize = dataSet.getNumInstances();

    Set<Integer> indexes = new HashSet<Integer>();

    Instances labeledInstances = new Instances(dataSet.getDataset(), sampleSize);

    for (int i = 0; i < sampleSize; i++) {

        int index = 0;

        if (getRandgen().uniform(0, 1) < biasToUniformClass) {

            // Pick a random class (of those classes that actually appear)
            int cIndex = getRandgen().choose(0, actualClasses);

            for (int j = 0, k = 0; j < classIndices.length - 1; j++) {
                if ((classIndices[j] != classIndices[j + 1]) && (k++ >= cIndex)) {
                    // Pick a random instance of the designated class
                    index = classIndices[j] + getRandgen().choose(0, classIndices[j + 1] - classIndices[j]);
                    break;
                }
            }
        } else {
            index = getRandgen().choose(0, originalSize);
        }

        labeledInstances.add((Instance) dataSet.instance(index).copy());
        indexes.add(index);
    }

    setLabeledData(new WekaDataset(labeledInstances));

    ArrayList<Container> indexesArray = new ArrayList<Container>();

    for (Integer i : indexes) {
        indexesArray.add(new Container(i, i));
    }

    //The array is ordered in descendent order
    OrderUtils.mergeSort(indexesArray, true);

    //Copy the entire dataset into unlabeled set
    Instances unlabeledInstances = new Instances(dataSet.getDataset());

    //remove the instances that have been selected previously
    for (Container pair : indexesArray) {
        unlabeledInstances.remove(Integer.parseInt(pair.getValue().toString()));
    }

    setUnlabeledData(new WekaDataset(unlabeledInstances));

    //clean up
    labeledInstances.clear();
    unlabeledInstances.clear();
    indexes.clear();
    indexesArray.clear();

    labeledInstances = null;
    unlabeledInstances = null;
    indexes = null;
    indexesArray = null;

}