Example usage for java.util List subList

List of usage examples for java.util List subList

Introduction

In this page you can find the example usage for java.util List subList.

Prototype

List<E> subList(int fromIndex, int toIndex);

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:com.simiacryptus.util.lang.CodeUtil.java

/**
 * Gets javadoc./*from   w  ww.j  ava  2 s  .  co  m*/
 *
 * @param clazz the clazz
 * @return the javadoc
 */
public static String getJavadoc(@Nullable final Class<?> clazz) {
    try {
        if (null == clazz)
            return null;
        @Nullable
        final File source = com.simiacryptus.util.lang.CodeUtil.findFile(clazz);
        if (null == source)
            return clazz.getName() + " not found";
        final List<String> lines = IOUtils.readLines(new FileInputStream(source), Charset.forName("UTF-8"));
        final int classDeclarationLine = IntStream.range(0, lines.size())
                .filter(i -> lines.get(i).contains("class " + clazz.getSimpleName())).findFirst().getAsInt();
        final int firstLine = IntStream.rangeClosed(1, classDeclarationLine).map(i -> classDeclarationLine - i)
                .filter(i -> !lines.get(i).matches("\\s*[/\\*@].*")).findFirst().orElse(-1) + 1;
        final String javadoc = lines.subList(firstLine, classDeclarationLine).stream()
                .filter(s -> s.matches("\\s*[/\\*].*")).map(s -> s.replaceFirst("^[ \t]*[/\\*]+", "").trim())
                .filter(x -> !x.isEmpty()).reduce((a, b) -> a + "\n" + b).orElse("");
        return javadoc.replaceAll("<p>", "\n");
    } catch (@javax.annotation.Nonnull final Throwable e) {
        e.printStackTrace();
        return "";
    }
}

From source file:exm.stc.ic.ICUtil.java

/**
 * Replace the current instruction with the provided sequence
 * After this is done, next() will return the instruction after
 * the inserted sequence/*  ww  w .  j  a  va2  s  . c o  m*/
 */
public static void replaceInsts(Block block, ListIterator<Statement> it,
        List<? extends Statement> replacements) {
    for (Statement stmt : replacements) {
        stmt.setParent(block);
    }
    if (replacements.size() == 1) {
        it.set(replacements.get(0));
    } else if (replacements.size() == 0) {
        it.remove();
    } else {
        it.set(replacements.get(0));
        List<? extends Statement> rest = replacements.subList(1, replacements.size());
        for (Statement newInst : rest) {
            it.add(newInst);
        }
    }
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Fetches the UUIDs of the given list of player names from the Mojang API.
 *
 * <p><b>WARNING: this method needs to be called from a dedicated thread, as the requests to
 * Mojang are executed directly in the current thread and, due to the Mojang API rate limit, the
 * thread may be frozen to wait a bit between requests if a lot of UUID are requested.</b></p>
 *
 * <p>You can use a {@link fr.zcraft.zlib.components.worker.Worker} to retrieve UUIDs.</p>
 *
 * This method may not be able to retrieve UUIDs for some players with old accounts. For them,
 * use {@link #fetchRemaining(Collection, Map)}.
 *
 * @param names          A list of player names.
 * @param limitByRequest The maximal number of UUID to retrieve per request.
 *
 * @return A map linking a player name to his Mojang {@link UUID}.
 * @throws IOException          If an exception occurs while contacting the Mojang API.
 * @throws InterruptedException If the thread is interrupted while sleeping when the system wait
 *                              because of the Mojang API rate limit.
 *//*from  ww  w . j  a v a2 s  . c o  m*/
static public Map<String, UUID> fetch(List<String> names, int limitByRequest)
        throws IOException, InterruptedException {
    Map<String, UUID> UUIDs = new HashMap<>();
    int requests = (names.size() / limitByRequest) + 1;

    List<String> tempNames;
    Map<String, UUID> tempUUIDs;

    for (int i = 0; i < requests; i++) {
        tempNames = names.subList(limitByRequest * i, Math.min((limitByRequest * (i + 1)) - 1, names.size()));
        tempUUIDs = rawFetch(tempNames);
        UUIDs.putAll(tempUUIDs);
        Thread.sleep(TIME_BETWEEN_REQUESTS);
    }

    return UUIDs;
}

From source file:com.pinterest.terrapin.tools.TerrapinAdmin.java

/**
 * Rollback file set to a specific version
 *
 * @param zkManager ZooKeeperManager instance
 * @param fileSet name of file set//from   ww w . j  av  a 2  s. co  m
 * @param fileSetInfo file set information
 * @param versionIndex index of version to be rolled back to
 * @throws IllegalArgumentException if version index is out of bound
 * @throws Exception if communication with ZooKeeper goes wrong
 */
public static void rollbackFileSet(ZooKeeperManager zkManager, String fileSet, FileSetInfo fileSetInfo,
        int versionIndex) throws Exception {
    List<FileSetInfo.ServingInfo> oldServingInfoList = fileSetInfo.oldServingInfoList;
    if (versionIndex >= 0 && versionIndex < oldServingInfoList.size()) {
        String currentHdfsPath = fileSetInfo.servingInfo.hdfsPath;
        String rollbackHdfsPath = oldServingInfoList.get(versionIndex).hdfsPath;
        fileSetInfo.servingInfo = oldServingInfoList.get(versionIndex);
        fileSetInfo.oldServingInfoList = oldServingInfoList.subList(versionIndex + 1,
                oldServingInfoList.size());
        zkManager.setFileSetInfo(fileSet, fileSetInfo);
        LOG.info(String.format("successfully rollback %s from %s to %s", fileSet, currentHdfsPath,
                rollbackHdfsPath));
    } else {
        throw new IllegalArgumentException("version index is out of bound");
    }
}

From source file:de.nava.informa.utils.AtomParserUtils.java

/**
 * Cuts all empty (whitespace) text blocks from the head and tail of contents list.
 *
 * @param contents list of contents.// ww w.  j ava2s  . c o m
 * @return trimmed version.
 */
public static List<Content> trimContents(List contents) {
    if (contents == null) {
        return null;
    }

    int head = 0;
    int count = contents.size();

    while ((head < count) && (contents.get(head) instanceof Text
            && (((Text) contents.get(head)).getTextTrim().length() == 0))) {
        head++;
    }

    int tail = count - 1;

    while ((tail > head) && (contents.get(tail) instanceof Text
            && (((Text) contents.get(tail)).getTextTrim().length() == 0))) {
        tail--;
    }

    return (tail >= head) ? contents.subList(head, tail + 1) : new ArrayList();
}

From source file:com.ponysdk.impl.query.memory.FilteringTools.java

public static <T> List<T> getPage(final int pageSize, final int page, final List<T> result) {
    if (result == null || result.size() == 0) {
        return result;
    }//from   w  w  w.  java  2 s .c  o m
    if (result.size() < pageSize)
        return result;
    if (page * pageSize > result.size()) {
        // return last page
        final int lastPage = result.size() / pageSize;
        return result.subList(lastPage * pageSize, result.size());
    }
    return new ArrayList<>(
            result.subList(page * pageSize, Math.min(result.size(), page * pageSize + pageSize)));
}

From source file:module.mailtracking.domain.CorrespondenceEntry.java

public static java.util.List<CorrespondenceEntry> getLastActiveEntriesSortedByDate(Integer numberOfEntries) {
    java.util.List<CorrespondenceEntry> entries = getActiveEntries();

    Collections.sort(entries, SORT_BY_WHEN_RECEIVED_COMPARATOR);

    return entries.subList(0, Math.min(entries.size(), numberOfEntries));
}

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.MongoLoader.java

public static void loadMongoData(MongoClientURI uri, final int NUM_WORKERS, Database database,
        final int numDocs, final PerfTestParent clazz) {
    logger.info("------------Loading Data into: " + database.name() + " with MONGO!------------");
    try {//from ww  w. j av  a  2 s  .  c  o  m
        try {
            MongoClient mongoClient = new MongoClient(uri);
            mongoClient.setWriteConcern(WriteConcern.MAJORITY);
            DB db = mongoClient.getDB(database.name());
            final DBCollection coll = db.getCollection(database.name());
            ArrayList<Thread> workers = new ArrayList<>(NUM_WORKERS + 1);
            int docsPerWorker = numDocs / NUM_WORKERS;
            try {
                List<Document> docs = clazz.getDocumentsFromFS();
                ArrayList<List<Document>> documentQueues = new ArrayList<>(NUM_WORKERS + 1);
                int numDocsAssigned = 0;
                while ((numDocsAssigned + 1) < numDocs) {
                    int start = numDocsAssigned;
                    int end = numDocsAssigned + docsPerWorker;
                    if (end > numDocs) {
                        end = numDocs - 1;
                    }
                    documentQueues.add(new ArrayList(docs.subList(start, end)));
                    numDocsAssigned = end;
                }
                for (final List<Document> queue : documentQueues) {
                    workers.add(new Thread() {
                        @Override
                        public void run() {
                            for (Document d : queue) {
                                DBObject o = (DBObject) JSON.parse(d.object());
                                coll.save(o);
                            }
                            logger.info("Thread " + Thread.currentThread().getName() + " is done. It processed "
                                    + queue.size() + " documents.");
                        }
                    });
                }
            } catch (UnsupportedOperationException e)//we can't read everything in at once
            {
                //all we need to do in this block is find a way to set "workers"
                for (int i = 0; i < NUM_WORKERS; i++) {
                    workers.add(new Thread() {
                        private final int chunk = (int) (Math.random() * 100) + 150;//pick a random chunk so we are not going back to the FS all at the same time and potentially causing a bottle neck

                        @Override
                        public void run() {
                            ThreadLocal<Integer> counter = new ThreadLocal<>();
                            counter.set(new Integer(0));
                            try {
                                List<Document> docs = clazz.getDocumentsFromFS(chunk);//grab a handful of documents
                                while (docs.size() > 0) {
                                    for (Document d : docs)//process the documents we grabbed
                                    {
                                        DBObject o = (DBObject) JSON.parse(d.object());
                                        coll.save(o);
                                        counter.set(counter.get() + 1);
                                    }
                                    docs = clazz.getDocumentsFromFS(chunk);//grab another handful of documents
                                }
                                logger.info("Thread " + Thread.currentThread().getName()
                                        + " is done. It processed " + counter.get() + " documents.");
                            } catch (IOException | ParseException e) {
                                logger.error("Couldn't read from document", e);
                            }
                        }
                    });
                }
            }

            long start = new Date().getTime();
            //start your threads!
            for (Thread t : workers) {
                t.start();
            }
            logger.info("All threads started, waiting for completion.");
            boolean allDone = false;
            boolean first = true;
            while (!allDone || first) {
                first = false;
                boolean done = true;
                for (Thread t : workers) {
                    if (t.isAlive()) {
                        done = false;
                        logger.info("Thread " + t.getName() + " is still running.");
                        break;
                    }
                }
                if (done) {
                    allDone = true;
                } else {
                    logger.info("We still have workers running...");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                }
            }
            long end = new Date().getTime();
            long miliseconds = end - start;
            double seconds = (double) miliseconds / 1000d;
            output.info("Done loading data using: " + NUM_WORKERS + ". Took: " + seconds + " seconds");
            double tpms = (double) numDocs / (double) miliseconds;
            double tps = tpms * 1000;
            double transactionTime = (double) miliseconds / (double) numDocs;
            output.info(database.name() + " Mongo Average Transactions Per Second: " + tps);
            output.info(
                    database.name() + " Mongo Average Transactions Time (in miliseconds): " + transactionTime);

        } catch (UnknownHostException e) {
            logger.error("Couldn't connect to Mongo Server", e);
        }
    } catch (IOException | ParseException e) {
        logger.error("Couldn't read data.", e);
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.LabeledTextCorpus.java

public static List<String> calculateNgrams(int nGramSize, List<String> sequence, String before) {
    List<String> text = new ArrayList<String>();
    int newNOfNGrams = Math.min(sequence.size(), nGramSize);
    if (newNOfNGrams > 0) {
        for (int i = newNOfNGrams; i <= sequence.size(); i++) {
            StringBuilder b = new StringBuilder();
            List<String> l = sequence.subList(i - newNOfNGrams, i);
            for (int j = 0; j < l.size(); j++) {
                b.append(l.get(j));/*  w  w  w.ja  v a2s  .  com*/
                if (j < l.size() - 1) {
                    b.append(COLON);
                }
            }
            text.add(before + b);
        }
    }
    return text;
}

From source file:Main.java

public static <E> Collection<List<E>> selectExactly(List<E> original, int nb) {
    if (nb < 0) {
        throw new IllegalArgumentException();
    }//from  w w  w . j  av  a2 s . c  om
    if (nb == 0) {
        return Collections.emptyList();
    }
    if (nb == 1) {
        final List<List<E>> result = new ArrayList<List<E>>();
        for (E element : original) {
            result.add(Collections.singletonList(element));
        }
        return result;

    }
    if (nb > original.size()) {
        return Collections.emptyList();
    }
    if (nb == original.size()) {
        return Collections.singletonList(original);
    }
    final List<List<E>> result = new ArrayList<List<E>>();

    for (List<E> subList : selectExactly(original.subList(1, original.size()), nb - 1)) {
        final List<E> newList = new ArrayList<E>();
        newList.add(original.get(0));
        newList.addAll(subList);
        result.add(Collections.unmodifiableList(newList));
    }
    result.addAll(selectExactly(original.subList(1, original.size()), nb));

    return Collections.unmodifiableList(result);
}