Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

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

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:org.proninyaroslav.libretorrent.fragments.AddTorrentFragment.java

private void buildTorrent() {
    AddTorrentFilesFragment fileFrag = (AddTorrentFilesFragment) adapter.getItem(FILE_FRAG_POS);
    AddTorrentInfoFragment infoFrag = (AddTorrentInfoFragment) adapter.getItem(INFO_FRAG_POS);

    if (fileFrag != null || infoFrag != null) {
        ArrayList<Integer> selectedIndexes = fileFrag.getSelectedFileIndexes();
        String downloadDir = infoFrag.getDownloadDir();
        String torrentName = infoFrag.getTorrentName();
        boolean sequentialDownload = infoFrag.isSequentialDownload();
        boolean startTorrent = infoFrag.startTorrent();

        if (info != null) {
            ArrayList<BencodeFileItem> files = info.getFiles();
            if (files.size() != 0 && selectedIndexes.size() != 0 && !TextUtils.isEmpty(torrentName)) {
                if (FileIOUtils.getFreeSpace(downloadDir) >= fileFrag.getSelectedFileSize()) {
                    Intent intent = new Intent();

                    ArrayList<Integer> priorities = new ArrayList<>(
                            Collections.nCopies(files.size(), Priority.IGNORE.swig()));

                    for (int index : selectedIndexes) {
                        priorities.set(index, Priority.NORMAL.swig());
                    }/*from   ww  w. jav  a  2s .  c  om*/

                    Torrent torrent = new Torrent(info.getSha1Hash(), torrentName, priorities, downloadDir);

                    torrent.setSequentialDownload(sequentialDownload);
                    torrent.setPaused(!startTorrent);
                    torrent.setTorrentFilePath(pathToTempTorrent);

                    intent.putExtra(AddTorrentActivity.TAG_RESULT_TORRENT, torrent);

                    finish(intent, FragmentCallback.ResultCode.OK);

                } else {
                    Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.error_free_space,
                            Snackbar.LENGTH_LONG);
                    snackbar.show();
                }

            } else {
                if (selectedIndexes.size() == 0) {
                    Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.error_no_files_selected,
                            Snackbar.LENGTH_LONG);
                    snackbar.show();
                }
            }
        }
    }
}

From source file:edu.uci.ics.hyracks.algebricks.core.algebra.operators.logical.visitors.SubstituteVariableVisitor.java

private void substInArray(ArrayList<LogicalVariable> varArray, LogicalVariable v1, LogicalVariable v2) {
    for (int i = 0; i < varArray.size(); i++) {
        LogicalVariable v = varArray.get(i);
        if (v == v1) {
            varArray.set(i, v2);
        }/*  w w w.j av a2  s  .  co  m*/
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.yahtzee2.subtask.StraightMdp.java

@Override
public Pair<ArrayList<YahtzeeDiceState>, ArrayList<Double>> sparseP(final YahtzeeDiceState s,
        final YahtzeeAction a) {
    final KeepAction ka = (KeepAction) a;
    final int Nrerolls = Hand.Ndice - ka.Nkeepers;
    final Fn.MultinomialTermGenerator g = new Fn.MultinomialTermGenerator(Nrerolls, Hand.Nfaces);

    final ArrayList<YahtzeeDiceState> ss = new ArrayList<YahtzeeDiceState>();
    final ArrayList<Double> P = new ArrayList<Double>();

    final double Z = Math.pow(Hand.Nfaces, Nrerolls);

    double sum = 0;
    while (g.hasNext()) {
        final int[] k = g.next();
        final double c = Fn.multinomialCoefficient(Nrerolls, k);
        Fn.vplus_inplace(k, ka.keepers);
        ss.add(new YahtzeeDiceState(new Hand(k), s.rerolls - 1));
        final double p = c / Z;
        sum += p;/*w w  w .j ava  2 s .co m*/
        P.add(p);
    }
    P.set(P.size() - 1, P.get(P.size() - 1) + (1.0 - sum)); // Ensure P is a proper distribution

    return Pair.makePair(ss, P);
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestEditLogRace.java

/**
 * The logSync() method in FSEditLog is unsynchronized whiel syncing
 * so that other threads can concurrently enqueue edits while the prior
 * sync is ongoing. This test checks that the log is saved correctly
 * if the saveImage occurs while the syncing thread is in the unsynchronized middle section.
 * /*from  w w w  .  ja v a  2s.  c  o  m*/
 * This replicates the following manual test proposed by Konstantin:
 *   I start the name-node in debugger.
 *   I do -mkdir and stop the debugger in logSync() just before it does flush.
 *   Then I enter safe mode with another client
 *   I start saveNamepsace and stop the debugger in
 *     FSImage.saveFSImage() -> FSEditLog.createEditLogFile()
 *     -> EditLogFileOutputStream.create() ->
 *     after truncating the file but before writing LAYOUT_VERSION into it.
 *   Then I let logSync() run.
 *   Then I terminate the name-node.
 *   After that the name-node wont start, since the edits file is broken.
 */
public void testSaveImageWhileSyncInProgress() throws Throwable {
    Configuration conf = getConf();
    NameNode.format(conf);
    NameNode fakeNN = mock(NameNode.class);
    NameNode.myMetrics = new NameNodeMetrics(conf, fakeNN);
    Mockito.doReturn(new InetSocketAddress("127.0.0.1", 12345)).when(fakeNN).getNameNodeAddress();

    final FSNamesystem namesystem = new FSNamesystem(fakeNN, conf);

    try {
        FSImage fsimage = namesystem.getFSImage();
        FSEditLog editLog = fsimage.getEditLog();

        ArrayList<EditLogOutputStream> streams = editLog.getEditStreams();
        EditLogOutputStream spyElos = spy(streams.get(0));
        streams.set(0, spyElos);

        final AtomicReference<Throwable> deferredException = new AtomicReference<Throwable>();
        final CountDownLatch waitToEnterFlush = new CountDownLatch(1);

        final Thread doAnEditThread = new Thread() {
            public void run() {
                try {
                    LOG.info("Starting mkdirs");
                    namesystem.mkdirs("/test",
                            new PermissionStatus("test", "test", new FsPermission((short) 00755)));
                    LOG.info("mkdirs complete");
                } catch (Throwable ioe) {
                    deferredException.set(ioe);
                    waitToEnterFlush.countDown();
                }
            }
        };

        Answer<Void> blockingFlush = new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                LOG.info("Flush called");
                if (Thread.currentThread() == doAnEditThread) {
                    LOG.info("edit thread: Telling main thread we made it to flush section...");
                    // Signal to main thread that the edit thread is in the racy section
                    waitToEnterFlush.countDown();
                    LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs");
                    Thread.sleep(BLOCK_TIME * 1000);
                    LOG.info("Going through to flush. This will allow the main thread to continue.");
                }
                invocation.callRealMethod();
                LOG.info("Flush complete");
                return null;
            }
        };
        doAnswer(blockingFlush).when(spyElos).flush();

        doAnEditThread.start();
        // Wait for the edit thread to get to the logsync unsynchronized section
        LOG.info("Main thread: waiting to enter flush...");
        waitToEnterFlush.await();
        if (deferredException.get() != null) {
            throw deferredException.get();
        }
        LOG.info("Main thread: detected that logSync is in unsynchronized section.");
        LOG.info("Trying to enter safe mode.");
        LOG.info("This should block for " + BLOCK_TIME + "sec, since flush will sleep that long");

        long st = System.currentTimeMillis();
        namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
        long et = System.currentTimeMillis();
        LOG.info("Entered safe mode");
        // Make sure we really waited for the flush to complete!
        assertTrue(et - st > (BLOCK_TIME - 1) * 1000);

        // Once we're in safe mode, save namespace.
        namesystem.saveNamespace();

        LOG.info("Joining on edit thread...");
        doAnEditThread.join();
        assertNull(deferredException.get());

        verifyEditLogs(fsimage);
    } finally {
        LOG.info("Closing namesystem");
        if (namesystem != null)
            namesystem.close();
    }
}

From source file:com.google.wolff.androidhunt.Hunt.java

/** Shuffles the clues.  Note that each clue is marked with
 *  a difficulty group, so that, say, a hard clue can't proceed
 *  an easier clue.//from   w  w w  .  java 2 s .  c o  m
 * @param seed The random number seed.
 */
public void shuffle(int seed) {
    if (isShuffled) {
        return;
    }
    // Divide into shuffle groups
    ArrayList<ArrayList<Clue>> groups = new ArrayList<ArrayList<Clue>>(10);

    for (int i = 0; i < 10; i++) {
        groups.add(null);
    }

    for (int i = 0; i < clueList.size(); i++) {
        Clue c = clueList.get(i);

        if (groups.get(c.shufflegroup) == null) {
            groups.set(c.shufflegroup, new ArrayList<Clue>());
        }

        groups.get(c.shufflegroup).add(c);
    }

    clueList = new ArrayList<Clue>();

    Random r = new Random(seed);

    for (int i = 0; i < 10; i++) {
        ArrayList<Clue> cl = groups.get(i);

        if (cl == null)
            continue;

        Collections.shuffle(cl, r);

        clueList.addAll(cl);
    }

    isShuffled = true;
}

From source file:org.nuxeo.tools.esync.db.DbSql.java

private String[] decodeAcl(String aclString) {
    ArrayList<String> acl = new ArrayList<>(Arrays.asList(StringUtils.split(aclString, ",")));
    // remove trailing -Everyone
    int lastAceIndex = acl.size() - 1;
    if (DENY_ALL.equals(acl.get(lastAceIndex))) {
        acl.remove(lastAceIndex);/*from ww w  .  j av  a  2 s  .  com*/
    }
    for (int i = 0; i < acl.size(); i++) {
        String ace = acl.get(i);
        if (ace.startsWith("-")) {
            acl.set(i, UNSUPPORTED_ACL);
        }
    }
    return acl.toArray(new String[acl.size()]);
}

From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneSearcherImpl.java

public ResultSet query(SearchParameters searchParameters) {
    if (searchParameters.getStores().size() != 1) {
        throw new IllegalStateException("Only one store can be searched at present");
    }// w  w w .  j a va  2  s.co  m

    ArrayList<StoreRef> stores = searchParameters.getStores();
    stores.set(0, tenantService.getName(searchParameters.getStores().get(0)));

    String parameterisedQueryString;
    if (searchParameters.getQueryParameterDefinitions().size() > 0) {
        Map<QName, QueryParameterDefinition> map = new HashMap<QName, QueryParameterDefinition>();

        for (QueryParameterDefinition qpd : searchParameters.getQueryParameterDefinitions()) {
            map.put(qpd.getQName(), qpd);
        }

        parameterisedQueryString = parameterise(searchParameters.getQuery(), map, null,
                namespacePrefixResolver);
    } else {
        parameterisedQueryString = searchParameters.getQuery();
    }
    // TODO: add another property so the set query is not changed ...
    // May be good to return the query as run ??
    searchParameters.setQuery(parameterisedQueryString);

    LuceneQueryLanguageSPI language = queryLanguages.get(searchParameters.getLanguage().toLowerCase());
    if (language != null) {
        return language.executeQuery(searchParameters, this);
    } else {
        throw new SearcherException("Unknown query language: " + searchParameters.getLanguage());
    }
}

From source file:com.example.customview.DynamicListView.java

private void swapElements(ArrayList arrayList, int indexOne, int indexTwo) {
    Object temp = arrayList.get(indexOne);
    arrayList.set(indexOne, arrayList.get(indexTwo));
    arrayList.set(indexTwo, temp);/*  ww  w.j  av  a 2  s  .  com*/
}

From source file:sawtooth.examples.xo.XoHandler.java

/**
 * Helper function to store state data./*from www .j  av  a2 s  .  c o  m*/
 */
private void storeGameData(String address, GameData gameData, String stateEntry, State stateStore)
        throws InternalError, InvalidTransactionException {
    String gameDataCsv = String.format("%s,%s,%s,%s,%s", gameData.gameName, gameData.board, gameData.state,
            gameData.playerOne, gameData.playerTwo);
    if (stateEntry.length() == 0) {
        stateEntry = gameDataCsv;
    } else {
        ArrayList<String> dataList = new ArrayList<>(Arrays.asList(stateEntry.split("\\|")));
        for (int i = 0; i <= dataList.size(); i++) {
            if (i == dataList.size()
                    || dataList.get(i).regionMatches(0, gameData.gameName, 0, gameData.gameName.length())) {
                dataList.set(i, gameDataCsv);
                break;
            }
        }
        stateEntry = StringUtils.join(dataList, "|");
    }

    ByteString csvByteString = ByteString.copyFromUtf8(stateEntry);
    Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<>(address, csvByteString);
    Collection<Map.Entry<String, ByteString>> addressValues = Collections.singletonList(entry);
    Collection<String> addresses = stateStore.set(addressValues);
    if (addresses.size() < 1) {
        throw new InternalError("State Error");
    }
}

From source file:com.ning.metrics.goodwill.store.CSVFileStore.java

@Override
public Collection<GoodwillSchema> getTypes() throws IOException {
    parseFile();/*from  w  w  w.ja v  a2 s  . com*/

    final ArrayList<GoodwillSchema> thriftTypesList = new ArrayList(goodwillSchemata.values());
    Collections.sort(thriftTypesList, new Comparator<GoodwillSchema>() {
        @Override
        public int compare(GoodwillSchema o, GoodwillSchema o1) {
            return o.getName().compareTo(o1.getName());
        }
    });

    if (sink != null) {
        for (int i = 0; i < thriftTypesList.size(); i++) {
            GoodwillSchema schema = thriftTypesList.get(i);
            schema.setSinkAddInfo(sink.addTypeInfo(schema));
            thriftTypesList.set(i, schema);

        }
    }

    return thriftTypesList;
}