List of usage examples for com.google.common.collect Sets newHashSetWithExpectedSize
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize)
From source file:org.attribyte.api.http.util.RobotsTxt.java
@SuppressWarnings("unchecked") /**/*from w w w . j a v a2s. co m*/ * Parse robots.txt from a character stream. * @param r A reader from which the <code>robots.txt</code> is read. * @param agents A list of user agents that, if listed in the file, should be preserved. * The wildcard (*) is always preserved. */ public RobotsTxt(final Reader r, final Set<String> agents) throws IOException { Set<String> preserveAgents = null; if (agents != null) { preserveAgents = Sets.newHashSetWithExpectedSize(agents.size() + 1); preserveAgents.add("*"); for (String agent : agents) { preserveAgents.add(agent.toLowerCase().trim()); } } List<String>[] currRecordLists = null; boolean newAgent = false; List<String> lines = CharStreams.readLines(r); for (String currLine : lines) { currLine = currLine.trim(); if (currLine.length() == 0 || currLine.startsWith("#")) { continue; } currLine = currLine.toLowerCase(); if (currLine.startsWith("user-agent")) { String currAgent = getValue(currLine); if (currAgent != null) { if (currRecordLists == null || newAgent) { currRecordLists = (ArrayList<String>[]) new ArrayList[2]; newAgent = false; } if (preserveAgents == null) { agentMap.put(currAgent, currRecordLists); } else if (preserveAgents.contains(currAgent)) { agentMap.put(currAgent, currRecordLists); } } } else if (currLine.startsWith("disallow")) { newAgent = true; String path = getValue(currLine); if (path == null || path.length() == 0) { path = EMPTY_PATH; } if (currRecordLists != null) { //Agent must have appeared first if (currRecordLists[DISALLOW] == null) { currRecordLists[DISALLOW] = new ArrayList<String>(8); } currRecordLists[DISALLOW].add(path); } } else if (currLine.startsWith("allow")) { newAgent = true; String path = getValue(currLine); if (path == null || path.length() == 0) { path = EMPTY_PATH; } if (currRecordLists != null) { if (currRecordLists[ALLOW] == null) { currRecordLists[ALLOW] = new ArrayList<String>(8); } currRecordLists[ALLOW].add(path); } } else { newAgent = true; //Ignore } } }
From source file:com.google.gerrit.server.git.HackPushNegotiateHook.java
private Set<ObjectId> history(Collection<Ref> refs, BaseReceivePack rp) { Set<ObjectId> alreadySending = rp.getAdvertisedObjects(); if (alreadySending.isEmpty()) { alreadySending = idsOf(refs);/*from w ww .j a va 2 s. co m*/ } int max = MAX_HISTORY - Math.max(0, alreadySending.size() - refs.size()); if (max <= 0) { return Collections.emptySet(); } // Scan history until the advertisement is full. RevWalk rw = rp.getRevWalk(); rw.reset(); try { for (Ref ref : refs) { try { if (ref.getObjectId() != null) { rw.markStart(rw.parseCommit(ref.getObjectId())); } } catch (IOException badCommit) { continue; } } Set<ObjectId> history = Sets.newHashSetWithExpectedSize(max); try { int stepCnt = 0; for (RevCommit c; history.size() < max && (c = rw.next()) != null;) { if (c.getParentCount() <= 1 && !alreadySending.contains(c) && (history.size() < BASE_COMMITS || (++stepCnt % STEP_COMMITS) == 0)) { history.add(c); } } } catch (IOException err) { log.error("error trying to advertise history", err); } return history; } finally { rw.reset(); } }
From source file:org.hudsonci.plugins.snapshotmonitor.internal.SnapshotMonitorImpl.java
public void update(final AbstractBuild build, final Collection<MavenCoordinatesDTO> dependencies) throws IOException { checkNotNull(build);/*from www.j a v a 2 s.c o m*/ checkNotNull(dependencies); if (!isConfigured()) { log.warn("SNAPSHOT monitor has not been configured"); return; } log.debug("Updating dependencies: {}", dependencies); Set<WatchedDependency> watched = Sets.newHashSetWithExpectedSize(dependencies.size()); for (MavenCoordinatesDTO dep : dependencies) { watched.add(new WatchedDependency(dep)); } try { update(watched); } catch (IOException e) { log.error("Failed to check last-modified for watched dependencies", e); } AbstractProject project = getProject(build); WatchedDependenciesProperty property = getWatchedDependenciesProperty(project); property.set(watched); project.save(); }
From source file:presto.android.gui.graph.NNode.java
public void addParent(NNode p) { if (p == this) { throw new RuntimeException("p.addView(p) for " + p); }/*from w ww . ja v a 2s . co m*/ if (p == null) { return; } if (parents == null) { parents = Sets.newHashSetWithExpectedSize(1); } parents.add(p); if (verbose) { System.out.println(this + " [p]==> " + p); } if (p.children == null) { p.children = Sets.newHashSet(); } p.children.add(this); }
From source file:com.kylinolap.dict.lookup.LookupTable.java
public Set<T> mapValues(String col, Set<T> values, String returnCol) { int colIdx = tableDesc.findColumnByName(col).getZeroBasedIndex(); int returnIdx = tableDesc.findColumnByName(returnCol).getZeroBasedIndex(); Set<T> result = Sets.newHashSetWithExpectedSize(values.size()); for (T[] row : data.values()) { if (values.contains(row[colIdx])) { result.add(row[returnIdx]);//from w w w . j ava 2s.c o m } } return result; }
From source file:org.gradoop.io.impl.tlf.functions.GraphTransactionFromTLFGraph.java
/** * In order to return the produced type one GraphTransaction has to be * initiated./*from w ww . j a v a2 s . c o m*/ */ private void prepareForProducedType() { Set<V> vertices = Sets.newHashSetWithExpectedSize(2); Set<E> edges = Sets.newHashSetWithExpectedSize(1); V source = this.vertexFactory.createVertex(); V target = this.vertexFactory.createVertex(); vertices.add(source); vertices.add(target); edges.add(this.edgeFactory.createEdge(source.getId(), target.getId())); graphTransaction = new GraphTransaction<G, V, E>(this.graphHeadFactory.initGraphHead(GradoopId.get()), vertices, edges); }
From source file:org.sosy_lab.cpachecker.pcc.strategy.parallel.interleaved.PartialReachedSetParallelIOCheckingInterleavedStrategy.java
@Override public boolean checkCertificate(final ReachedSet pReachedSet) throws CPAException, InterruptedException { AtomicBoolean checkResult = new AtomicBoolean(true); Semaphore partitionChecked = new Semaphore(0); Semaphore partitionsRead = new Semaphore(0); Collection<AbstractState> certificate = Sets.newHashSetWithExpectedSize(ioHelper.getNumPartitions()); Multimap<CFANode, AbstractState> partitionNodes = HashMultimap.create(); Collection<AbstractState> inOtherPartition = new ArrayList<>(); AbstractState initialState = pReachedSet.popFromWaitlist(); Precision initPrec = pReachedSet.getPrecision(initialState); Lock lock = new ReentrantLock(); ExecutorService executor = null, readExecutor = null, checkExecutor = null; logger.log(Level.INFO, "Create and start threads"); try {/*from w w w. j a v a 2 s . com*/ if (numReadThreads == 0) { executor = Executors.newFixedThreadPool(numThreads); startReadingThreads(numThreads, executor, checkResult, partitionsRead, partitionChecked); startCheckingThreads(numThreads, executor, checkResult, partitionsRead, partitionChecked, certificate, partitionNodes, inOtherPartition, initPrec, lock); } else { readExecutor = Executors.newFixedThreadPool(numReadThreads); startReadingThreads(numReadThreads, readExecutor, checkResult, partitionsRead, partitionChecked); checkExecutor = Executors.newFixedThreadPool(numThreads - numReadThreads); startCheckingThreads(numThreads - numReadThreads, checkExecutor, checkResult, partitionsRead, partitionChecked, certificate, partitionNodes, inOtherPartition, initPrec, lock); } partitionChecked.acquire(ioHelper.getNumPartitions()); if (!checkResult.get()) { return false; } logger.log(Level.INFO, "Add initial state to elements for which it will be checked if they are covered by partition nodes of certificate."); inOtherPartition.add(initialState); logger.log(Level.INFO, "Check if initial state and all nodes which should be contained in different partition are covered by certificate (partition node)."); if (!PartitionChecker.areElementsCoveredByPartitionElement(inOtherPartition, partitionNodes, cpa.getStopOperator(), initPrec)) { logger.log(Level.SEVERE, "Initial state or a state which should be in other partition is not covered by certificate."); return false; } logger.log(Level.INFO, "Check property."); stats.getPropertyCheckingTimer().start(); try { if (!cpa.getPropChecker().satisfiesProperty(certificate)) { logger.log(Level.SEVERE, "Property violated"); return false; } } finally { stats.getPropertyCheckingTimer().stop(); } return true; } finally { if (executor != null) { executor.shutdown(); } if (readExecutor != null) { readExecutor.shutdown(); } if (checkExecutor != null) { checkExecutor.shutdown(); } } }
From source file:com.github.steveash.jg2p.train.JointEncoderTrainer.java
private Collection<Alignment> makeCrfExamplesFromAlignTag(List<InputRecord> inputs, Set<Alignment> goodExamples, Aligner crfAligner, AlignModel mlAligner, TrainOptions opts) { // this is a little complicated; we want to use the goodExamples (supervised aligns) if we have it; next use the // crfAligner if it produces a good alignment that matches the Y count; else use the mlAligner Set<Alignment> result = Sets.newHashSetWithExpectedSize(inputs.size()); List<InputRecord> failedInputs = Lists.newArrayList(); Map<Pair<Word, Word>, Alignment> supervisedAligns = makeSupervisedAlignsMap(goodExamples); int superHit = 0; int xyEqualCount = 0; int crfAlignHit = 0; int mlAlignHit = 0; for (InputRecord input : inputs) { Alignment maybeSuper = supervisedAligns.get(input.xyWordPair()); if (maybeSuper != null) { superHit += 1;// w ww . j a v a 2s.co m result.add(maybeSuper); continue; } if (input.xWord.unigramCount() == input.yWord.unigramCount()) { // no alignment necessary its already aligned result.add(new Alignment(input.xWord, Zipper.up(input.xWord, input.yWord), 0.0)); xyEqualCount += 1; continue; } Alignment maybeCrf = makeCrfAlign(crfAligner, input); if (maybeCrf != null) { crfAlignHit += 1; result.add(maybeCrf); continue; } mlAlignHit += 1; failedInputs.add(input); } List<Alignment> mlAligns = makeCrfExamples(failedInputs, mlAligner, opts); result.addAll(mlAligns); log.info("Super/Eq/Crf/ML " + superHit + "/" + xyEqualCount + "/" + crfAlignHit + "/" + mlAlignHit + " ML added count " + mlAligns.size()); return result; }
From source file:org.sakaiproject.nakamura.calendar.LiteCalendarServiceImpl.java
/** * {@inheritDoc}// w w w. ja va 2s. c om * @see org.sakaiproject.nakamura.api.calendar.LiteCalendarService#export(Session, org.sakaiproject.nakamura.api.lite.content.Content, java.lang.String[]) */ public Calendar export(Session session, Content node, String[] types) throws CalendarException { // Translate input type strings (e.g., "VEVENT") into Sling resource types // (e.g., "sakai/calendar-vevent"). Set<String> wantedResourceTypes = Sets.newHashSetWithExpectedSize(types.length); for (String type : types) { wantedResourceTypes.add(SAKAI_CALENDAR_RT + "-" + type.toLowerCase()); } // Start constructing the iCal Calendar. Calendar calendar = new Calendar(); PropertyFactory propFactory = PropertyFactoryImpl.getInstance(); try { // Add any Calendar properties. addNodePropertiesToCal(node, calendar.getProperties(), propFactory); // Traverse the tree. Iterable<Content> children = node.listChildren(); for (Content childContent : children) { recurseForEvents(childContent, calendar, propFactory, wantedResourceTypes); } } catch (IOException e) { LOGGER.error("Caught an IOException when trying to export a calendar", e); throw new CalendarException(500, e.getMessage()); } catch (URISyntaxException e) { LOGGER.error("Caught a URISyntaxException when trying to export a calendar", e); throw new CalendarException(500, e.getMessage()); } catch (ParseException e) { LOGGER.error("Caught a ParseException when trying to export a calendar", e); throw new CalendarException(500, e.getMessage()); } return calendar; }
From source file:com.pinterest.terrapin.controller.TerrapinRoutingTableProvider.java
@VisibleForTesting public void updateExternalView(List<ExternalView> externalViewList) { Set<String> resourceSet = Sets.newHashSetWithExpectedSize(externalViewList.size()); synchronized (viewInfoRecordMap) { for (ExternalView externalView : externalViewList) { if (externalView == null) { continue; }/* ww w.jav a2 s . com*/ String resource = externalView.getResourceName(); resourceSet.add(resource); ViewInfoRecord record = viewInfoRecordMap.get(resource); ViewInfoRecord newRecord = new ViewInfoRecord(); newRecord.viewInfo = new ViewInfo(externalView); if (record != null) { // Only put stuff to be drained if the new external view does not equal the // previous external view. if (newRecord.viewInfo.equals(record.viewInfo)) continue; } newRecord.drained = false; viewInfoRecordMap.put(resource, newRecord); } // Finally remove any deleted external views from the map. Set<String> resourcesToRemove = Sets.newHashSetWithExpectedSize(viewInfoRecordMap.size()); for (String resource : viewInfoRecordMap.keySet()) { if (!resourceSet.contains(resource)) { resourcesToRemove.add(resource); } } for (String resource : resourcesToRemove) { this.viewInfoRecordMap.remove(resource); } } }