List of usage examples for java.util Deque add
boolean add(E e);
From source file:org.jasig.portal.layout.TransientUserLayoutXMLEventReader.java
@Override protected Deque<XMLEvent> getAdditionalEvents(XMLEvent event) { if (event.isStartElement()) { final StartElement startElement = event.asStartElement(); //All following logic requires an ID attribute, ignore any element without one final Attribute idAttribute = startElement.getAttributeByName(IUserLayoutManager.ID_ATTR_NAME); if (idAttribute == null) { return null; }//from w w w . jav a 2 s .c o m //Handle adding a transient folder to the root element if (this.rootFolderId.equals(idAttribute.getValue())) { final QName name = startElement.getName(); final String namespaceURI = name.getNamespaceURI(); final String prefix = name.getPrefix(); final Deque<XMLEvent> transientEventBuffer = new LinkedList<XMLEvent>(); final Collection<Attribute> transientFolderAttributes = new LinkedList<Attribute>(); transientFolderAttributes.add( EVENT_FACTORY.createAttribute("ID", TransientUserLayoutManagerWrapper.TRANSIENT_FOLDER_ID)); transientFolderAttributes.add(EVENT_FACTORY.createAttribute("type", "regular")); transientFolderAttributes.add(EVENT_FACTORY.createAttribute("hidden", "true")); transientFolderAttributes.add(EVENT_FACTORY.createAttribute("unremovable", "true")); transientFolderAttributes.add(EVENT_FACTORY.createAttribute("immutable", "true")); transientFolderAttributes.add(EVENT_FACTORY.createAttribute("name", "Transient Folder")); final StartElement transientFolder = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.FOLDER, transientFolderAttributes.iterator(), null); transientEventBuffer.add(transientFolder); //append channel element iff subscribeId describes a transient channel, and not a regular layout channel final String subscribeId = this.userLayoutManager.getFocusedId(); if (null != subscribeId && !subscribeId.equals("") && this.userLayoutManager.isTransientChannel(subscribeId)) { IPortletDefinition chanDef = null; try { chanDef = this.userLayoutManager.getChannelDefinition(subscribeId); } catch (Exception e) { this.logger.error("Could not obtain IChannelDefinition for subscribe id: " + subscribeId, e); } if (chanDef != null) { //TODO Move IChannelDefinition/IPortletDefinition -> StAX events code somewhere reusable final Collection<Attribute> channelAttrs = new LinkedList<Attribute>(); channelAttrs.add(EVENT_FACTORY.createAttribute("ID", subscribeId)); channelAttrs.add(EVENT_FACTORY.createAttribute("typeID", Integer.toString(chanDef.getType().getId()))); channelAttrs.add(EVENT_FACTORY.createAttribute("hidden", "false")); channelAttrs.add(EVENT_FACTORY.createAttribute("unremovable", "true")); channelAttrs.add(EVENT_FACTORY.createAttribute("name", chanDef.getName())); channelAttrs.add(EVENT_FACTORY.createAttribute("description", chanDef.getDescription())); channelAttrs.add(EVENT_FACTORY.createAttribute("title", chanDef.getTitle())); channelAttrs.add(EVENT_FACTORY.createAttribute("chanID", chanDef.getPortletDefinitionId().getStringId())); channelAttrs.add(EVENT_FACTORY.createAttribute("fname", chanDef.getFName())); channelAttrs.add( EVENT_FACTORY.createAttribute("timeout", Integer.toString(chanDef.getTimeout()))); channelAttrs.add(EVENT_FACTORY.createAttribute("transient", "true")); final StartElement startChannel = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.CHANNEL, channelAttrs.iterator(), null); transientEventBuffer.offer(startChannel); // add channel parameter elements for (final IPortletDefinitionParameter parm : chanDef.getParameters()) { final Collection<Attribute> parameterAttrs = new LinkedList<Attribute>(); parameterAttrs.add(EVENT_FACTORY.createAttribute("name", parm.getName())); parameterAttrs.add(EVENT_FACTORY.createAttribute("value", parm.getValue())); final StartElement startParameter = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.PARAMETER, parameterAttrs.iterator(), null); transientEventBuffer.offer(startParameter); final EndElement endParameter = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.PARAMETER, null); transientEventBuffer.offer(endParameter); } final EndElement endChannel = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.CHANNEL, null); transientEventBuffer.offer(endChannel); } } final EndElement endFolder = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.FOLDER, null); transientEventBuffer.offer(endFolder); return transientEventBuffer; } } return null; }
From source file:edu.berkeley.compbio.phyloutils.HugenholtzTaxonomyService.java
@NotNull private synchronized Integer getUniqueNodeForMultilevelName(String[] taxa) throws NoSuchNodeException { List<String> reverseTaxa = new ArrayList(Arrays.asList(taxa.clone())); Collections.reverse(reverseTaxa); //final String firstS = reverseTaxa.remove(0); //Collection<Integer> trav = null; // = nameToIdMap.get(firstS); /*while (trav.isEmpty()) {//w ww. j a v a 2 s .c om logger.warn("IGNORING Node " + s + " not found in " + DSStringUtils.join(taxa, "; ")); continue; } */ Set<Deque<Integer>> paths = null; HashMultimap<String, Integer> nameToIdsMap = (HashMultimap<String, Integer>) nameToIdsMapStub.get(); HashMultimap<String, Integer> extraNameToIdsMap = (HashMultimap<String, Integer>) extraNameToIdsMapStub .get(); for (String s : reverseTaxa) { Collection<Integer> matchingNodes = nameToIdsMap.get(s); if (matchingNodes.isEmpty()) { matchingNodes = extraNameToIdsMap.get(s); } if (matchingNodes.isEmpty()) { logger.debug("IGNORING Node " + s + " not found in " + DSStringUtils.join(taxa, "; ")); } else { // Set<Integer> nextTrav = new HashSet<Integer>(); if (paths == null) { paths = new HashSet<Deque<Integer>>(matchingNodes.size()); //nextTrav.addAll(matchingNodes); for (Integer node : matchingNodes) { Deque<Integer> l = new LinkedList<Integer>(); l.add(node); paths.add(l); } } else { BasicRootedPhylogeny<Integer> theIntegerTree = (BasicRootedPhylogeny<Integer>) theIntegerTreeStub .get(); Set<Deque<Integer>> okPaths = new HashSet<Deque<Integer>>(); for (Deque<Integer> path : paths) { Integer descendant = path.peek(); for (Integer ancestor : matchingNodes) { if (theIntegerTree.isDescendant(ancestor, descendant)) { path.addFirst(ancestor); okPaths.add(path); } } } paths = okPaths; // ditch any paths that didn't have an ancestor added this round } if (paths.isEmpty()) { // we get here only if // a) there was more than one live path on the last round // b) none of those paths are descendants of the matches at the current level throw new NoSuchNodeException( "Requested classification path does not match tree: " + DSStringUtils.join(taxa, "; ")); } // if all the paths converge on exactly one node, call it a match, even if higher levels of the tree don't match. if (matchingNodes.size() == 1) { return commonAncestor(paths); } } } throw new NoSuchNodeException("Multiple distinct matching paths: " + DSStringUtils.join(taxa, "; ")); //return commonAncestor(paths); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity.TestProportionalCapacityPreemptionPolicy.java
ParentQueue mockParentQueue(ParentQueue p, int subqueues, Deque<ParentQueue> pqs) { ParentQueue pq = mock(ParentQueue.class); List<CSQueue> cqs = new ArrayList<CSQueue>(); when(pq.getChildQueues()).thenReturn(cqs); for (int i = 0; i < subqueues; ++i) { pqs.add(pq); }/*from ww w . j a v a2s . c om*/ if (p != null) { p.getChildQueues().add(pq); } return pq; }
From source file:com.skelril.skree.content.world.wilderness.WildernessWorldWrapper.java
private PlayerCombatParser createFor(Cancellable event, int level) { return new PlayerCombatParser() { @Override//from w w w .j a v a 2s .co m public void processPvP(Player attacker, Player defender) { if (allowsPvP(level)) { return; } Optional<PvPService> optService = Sponge.getServiceManager().provide(PvPService.class); if (optService.isPresent()) { PvPService service = optService.get(); if (service.getPvPState(attacker).allowByDefault() && service.getPvPState(defender).allowByDefault()) { return; } } attacker.sendMessage(Text.of(TextColors.RED, "PvP is opt-in only in this part of the Wilderness!")); attacker.sendMessage( Text.of(TextColors.RED, "Mandatory PvP is from level ", getFirstPvPLevel(), " and on.")); event.setCancelled(true); } @Override public void processMonsterAttack(Living attacker, Player defender) { if (!(event instanceof DamageEntityEvent)) { return; } DamageEntityEvent dEvent = (DamageEntityEvent) event; // If they're endermites they hit through armor, otherwise they get a damage boost if (attacker.getType() == EntityTypes.ENDERMITE) { for (Tuple<DamageModifier, Function<? super Double, Double>> modifier : dEvent.getModifiers()) { dEvent.setDamage(modifier.getFirst(), (a) -> 0D); } dEvent.setBaseDamage(1); } else { dEvent.setBaseDamage(dEvent.getBaseDamage() + getDamageMod(level)); } // Only apply scoring while in survival mode if (defender.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(defender.getUniqueId()); if (meta != null) { meta.hit(); } } @Override public void processPlayerAttack(Player attacker, Living defender) { Task.builder().delayTicks(1) .execute(() -> healthPrinter.print(MessageChannel.fixed(attacker), defender)) .submit(SkreePlugin.inst()); if (!(defender instanceof Monster) || defender instanceof Creeper) { return; } // Only apply scoring while in survival mode if (attacker.get(Keys.GAME_MODE).orElse(GameModes.SURVIVAL) != GameModes.SURVIVAL) { return; } WildernessPlayerMeta meta = playerMetaMap.get(attacker.getUniqueId()); if (meta != null) { meta.attack(); if (meta.getRatio() > 30 && meta.getFactors() > 35) { Deque<Entity> spawned = new ArrayDeque<>(); for (int i = Probability.getRandom(5); i > 0; --i) { Entity entity = attacker.getWorld().createEntity(EntityTypes.ENDERMITE, defender.getLocation().getPosition()); entity.getWorld().spawnEntity(entity, Cause.source(SpawnCause.builder().type(SpawnTypes.PLUGIN).build()).build()); spawned.add(entity); } IntegratedRunnable runnable = new IntegratedRunnable() { @Override public boolean run(int times) { Entity mob = spawned.poll(); if (mob.isLoaded() && mob.getWorld().equals(attacker.getWorld())) { mob.setLocation(attacker.getLocation()); } return true; } @Override public void end() { } }; TimedRunnable timedRunnable = new TimedRunnable<>(runnable, spawned.size()); timedRunnable.setTask(Task.builder().execute(timedRunnable).delayTicks(40).intervalTicks(20) .submit(SkreePlugin.inst())); } if (System.currentTimeMillis() - meta.getLastReset() >= TimeUnit.MINUTES.toMillis(5)) { meta.reset(); } } } }; }
From source file:org.gdms.source.DefaultSourceManager.java
private void removeFromSchema(String name) { if (name.isEmpty()) { throw new IllegalArgumentException("Empty table name!"); }/*w w w .j a va 2 s.c o m*/ // split on the dots '.' into // schema1.schema2.schema3.table1 String[] l = DOT.split(name); if (l.length <= 1) { // just a table, we remove it from the root schema schema.removeTable(name); } else { Deque<Schema> path = new ArrayDeque<Schema>(); path.add(schema); // we get down // to the last schema before the table for (int i = 0; i < l.length - 1; i++) { final Schema n = path.getFirst().getSubSchemaByName(l[i]); path.addFirst(n); } boolean stop = false; while (!path.isEmpty() && !stop) { // take the last schema in the path (top of the pile) final Schema n = path.pollFirst(); n.removeTable(l[l.length - 1]); if (n.getTableCount() != 0 || n.getSubSchemaNames().length != 0) { // the schema is still needed, we must not remove it stop = true; } else { Schema p = n.getParentSchema(); if (p != null) { p.removeSubSchema(n.getName()); } else { // we have reached root, it stays were it is... stop = true; } } } } }
From source file:org.ops4j.pax.url.mvn.internal.AetherBasedResolver.java
private void releaseSession(RepositorySystemSession session) { LocalRepository repo = session.getLocalRepository(); Deque<RepositorySystemSession> deque = sessions.get(repo); if (deque == null) { sessions.putIfAbsent(repo, new ConcurrentLinkedDeque<RepositorySystemSession>()); deque = sessions.get(repo);//w w w . j a v a 2s . c o m } session.getData().set(SESSION_CHECKS, null); deque.add(session); }
From source file:com.darkstar.beanCartography.utils.finder.Finder.java
/** * Process the bean context stack./*from w w w .j ava 2 s.c o m*/ * * @param stack stack of objects left to search * @param visited set of objects already searched */ protected void visit(Deque<BeanContext> stack, Set<BeanContext> visited) { BeanContext target = stack.pop(); if (target == null) return; if (visited.contains(target)) return; visited.add(target); // process this object and check the filters. if passed filter then run interceptors... filtersInterceptors.entrySet().stream().filter(entry -> entry.getKey().accept(target.getSource())) .forEach(entry -> entry.getValue().intercept(target.getSource())); // process this object's contained objects (i.e. see what we need to add to the stack)... if (NameUtils.isImmutable(target.getSource().getClass())) return; Object fieldValue = null; try { while (target.hasNextFieldValue()) { fieldValue = target.nextFieldValue(); // skip nulls... if (fieldValue == null) continue; // add pojo or container or whatever this is... if (!visited.contains(fieldValue) && !stack.contains(fieldValue)) stack.add(new BeanContext(fieldValue)); // arrays... if (fieldValue.getClass().isArray()) { if (!processArrays) continue; final Object arrayFieldValue = fieldValue; IntStream.range(0, Array.getLength(arrayFieldValue)).forEach(i -> { Object element = Array.get(arrayFieldValue, i); if (element != null && !visited.contains(element) && !stack.contains(element)) stack.add(new BeanContext(element)); }); // collections... } else if (fieldValue instanceof Collection<?>) { if (!processCollections) continue; ((Collection<?>) fieldValue).stream().filter( element -> element != null && !visited.contains(element) && !stack.contains(element)) .forEach(element -> stack.add(new BeanContext(element))); // maps... } else if (fieldValue instanceof Map<?, ?>) { if (!processMaps) continue; ((Map<?, ?>) fieldValue).entrySet().stream().forEach(entry -> { if (entry.getKey() != null && !visited.contains(entry.getKey()) && !stack.contains(entry.getKey())) stack.add(new BeanContext(entry.getKey())); if (entry.getValue() != null && !visited.contains(entry.getValue()) && !stack.contains(entry.getValue())) stack.add(new BeanContext(entry.getValue())); }); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:uniol.apt.analysis.synthesize.separation.KBoundedSeparation.java
private void generateAllRegions(int k) { assert k >= 1; Set<Bag<State>> known = new HashSet<>(); Deque<Bag<State>> todo = new LinkedList<>(); addExcitationAndSwitchingRegions(known); todo.addAll(known);//from w w w . j av a 2 s . c o m while (!todo.isEmpty()) { InterrupterRegistry.throwIfInterruptRequestedForCurrentThread(); Bag<State> r = todo.removeFirst(); debug(); debugFormat("Examining %s", r); Pair<Event, Integer> event = findEventWithNonConstantGradient(r); if (event == null) { debug("It is a region!"); regions.add(convertToRegion(r)); continue; } // Expand (= add entries) to the multiset so that it becomes "more region-like". // To do this, we either want to go towards a region with gradient(event) <= g or // gradient(event) > g. These two cases follow. Bag<State> r1 = expandBelowOrEqual(r, event.getFirst(), event.getSecond()); debugFormat("for gradient(%s) <= %d, new result is %s", event.getFirst(), event.getSecond(), r1); if (shouldExplore(r1, k) && known.add(r1)) todo.add(r1); else debug("...which should not be explored"); Bag<State> r2 = expandAboveOrEqual(r, event.getFirst(), event.getSecond() + 1); debugFormat("for gradient(%s) >= %d, new result is %s", event.getFirst(), event.getSecond() + 1, r2); if (shouldExplore(r2, k) && known.add(r2)) todo.add(r2); else debug("...which should not be explored"); } debugFormat("Found the following regions: %s", regions); }
From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java
/** * Step 4: assign elevation//from ww w . ja v a 2 s . co m */ private void assignElevation() { if (graph == null) { return; } Random rand = new Random(seed * 2); //initialize border corners with zero elevation Deque<Graph.Corner> q = new ArrayDeque<>(); for (Graph.Corner c : graph.corners) { if (c.border) { c.elevation = 0; q.add(c); } else { c.elevation = Float.POSITIVE_INFINITY; } } // Traverse the graph and assign elevations to each point. As we // move away from the map border, increase the elevations. This // guarantees that rivers always have a way down to the coast by // going downhill (no local minima). while (!q.isEmpty()) { Graph.Corner c = q.poll(); for (Graph.Corner a : c.adjacent) { if (c.ocean && a.ocean && a.elevation > 0) { a.elevation = 0; q.addFirst(a); continue; } float elevation = c.elevation + (a.ocean ? 0 : 0.01f); if (!c.water && !a.water) { elevation += 1; } //add some more randomness //elevation += rand.nextDouble()/4; if (elevation < a.elevation) { a.elevation = elevation; q.add(a); } } } //redistribute elevation float SCALE_FACTOR = 1.1f; ArrayList<Graph.Corner> corners = new ArrayList<>(); for (Graph.Corner c : graph.corners) { if (!c.ocean) { corners.add(c); } } Collections.sort(corners, new Comparator<Graph.Corner>() { @Override public int compare(Graph.Corner o1, Graph.Corner o2) { return Float.compare(o1.elevation, o2.elevation); } }); for (int i = 0; i < corners.size(); i++) { // Let y(x) be the total area that we want at elevation <= x. // We want the higher elevations to occur less than lower // ones, and set the area to be y(x) = 1 - (1-x)^2. float y = (float) i / (float) (corners.size() - 1); float x = (float) (Math.sqrt(SCALE_FACTOR) - Math.sqrt(SCALE_FACTOR * (1 - y))); if (x > 1.0) x = 1; // TODO: does this break downslopes? corners.get(i).elevation = x; } assignCenterElevations(); //update mesh updateElevationGeometry(); }
From source file:com.yangtsaosoftware.pebblemessenger.services.PebbleCenter.java
private List<PebbleMessage> splitPages(PebbleMessage tmpPM) { List<PebbleMessage> pmPages = new ArrayList<PebbleMessage>(); String[] splitString = tmpPM.getAscMsg().split("\n"); Constants.log(TAG_NAME, tmpPM.getAscMsg()); for (String str : splitString) { Constants.log(TAG_NAME, "splitPages, deal:" + str); }//w w w .ja v a2 s . c o m int pageCount = bigInt((float) splitString.length / (float) fLines); for (int page = 1; page <= pageCount; page++) { PebbleMessage itemPm = new PebbleMessage(); itemPm.set_id(tmpPM.get_id()); StringBuilder tmpSB = new StringBuilder(); for (int line = (page - 1) * fLines; line < (page * fLines > splitString.length ? splitString.length : page * fLines); line++) { tmpSB.append(splitString[line]); tmpSB.append('\n'); } itemPm.setAscMsg(tmpSB.toString()); Deque<CharacterMatrix> itemDqCM = new ArrayDeque<CharacterMatrix>(); while (!tmpPM.getCharacterQueue().isEmpty()) { CharacterMatrix tmpCM = tmpPM.getCharacterQueue().pollFirst(); if (tmpCM.getPos()[0] >= (page - 1) * fLines && tmpCM.getPos()[0] <= page * fLines) { itemDqCM.add(tmpCM); } else { tmpPM.getCharacterQueue().addFirst(tmpCM); break; } } itemPm.setCharacterQueue(itemDqCM); pmPages.add(page - 1, itemPm); } return pmPages; }