public static void main(String[] args) { int n = 10000; if (args.length > 0) n = Integer.parseInt(args[0]); List<Integer> sorted = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) sorted.add(new Integer(i)); List<Integer> shuffled = new ArrayList<Integer>(sorted); Collections.shuffle(shuffled); Queue<Integer> pq = new PriorityQueue<Integer>(n, new MyComparator()); for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); ) pq.add(i.next()); List<Integer> recons = new ArrayList<Integer>(); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); recons.clear(); pq = new PriorityQueue<Integer>(shuffled); while (!pq.isEmpty()) recons.add(pq.remove()); if (!recons.equals(sorted)) throw new RuntimeException("Sort test failed"); // Remove all odd elements from queue pq = new PriorityQueue<Integer>(shuffled); for (Iterator<Integer> i = pq.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); recons.clear(); while (!pq.isEmpty()) recons.add(pq.remove()); for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); ) if ((i.next().intValue() & 1) == 1) i.remove(); if (!recons.equals(sorted)) throw new RuntimeException("Iterator remove test failed."); }
@Override public void update(GameContainer gc, int delta) throws SlickException { rand.nextDouble(); if (System.currentTimeMillis() - lastUpdate > simulationDelay) { lastUpdate = System.currentTimeMillis(); runSimulation(); } Airplane airplaneHandle; Iterator<Airplane> it; it = airQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.update(delta); } it = groundQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.update(delta); } airplaneHandle = runway.getCurrentAirplane(); if (airplaneHandle != null) airplaneHandle.update(delta); }
@Override public void render(GameContainer gc, Graphics g) throws SlickException { backgroundImage.draw(); Airplane airplaneHandle; Iterator<Airplane> it; it = airQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.render(g, airplaneImage); } it = groundQueue.iterator(); while (it.hasNext()) { airplaneHandle = it.next(); airplaneHandle.render(g, airplaneImage); } airplaneHandle = runway.getCurrentAirplane(); if (airplaneHandle != null) airplaneHandle.render(g, airplaneImage); g.setColor(Color.white); g.drawString("Airport Simulator", gc.getWidth() - 170, 10); g.drawString("Update: " + currentUpdate, gc.getWidth() - 130, gc.getHeight() - 30); }
public static void assertEqual(Queue<NdPoint> expected, Queue<NdPoint> actual) { String error = String.format("expected: %s but was: %s", expected, actual); assertEquals(error, expected.size(), actual.size()); Iterator<NdPoint> iexpect = expected.iterator(); Iterator<NdPoint> iactual = actual.iterator(); while (iexpect.hasNext()) { NdPoint e = iexpect.next(); NdPoint a = iactual.next(); assertTrue(error, e.equals(a)); } }
void checkIterationSanity(Queue q) { if (rnd.nextBoolean()) return; int size = q.size(); Object[] a = q.toArray(); Object[] b = new Object[size + 2]; Arrays.fill(b, Boolean.TRUE); Object[] c = q.toArray(b); equal(a.length, size); check(b == c); check(b[size] == null); check(b[size + 1] == Boolean.TRUE); equal(q.toString(), Arrays.toString(a)); Integer[] xx = null, yy = null; if (size > 0) { xx = new Integer[size - 1]; Arrays.fill(xx, 42); yy = ((Queue<Integer>) q).toArray(xx); for (Integer zz : xx) equal(42, zz); } Iterator it = q.iterator(); for (int i = 0; i < size; i++) { check(it.hasNext()); Object x = it.next(); check(x == a[i]); check(x == b[i]); if (xx != null) check(x == yy[i]); } check(!it.hasNext()); }
public MessageReference removeReferenceByID(final long messageID) throws Exception { if (browseOnly) { return null; } // Expiries can come in out of sequence with respect to delivery order Iterator<MessageReference> iter = deliveringRefs.iterator(); MessageReference ref = null; while (iter.hasNext()) { MessageReference theRef = iter.next(); if (theRef.getMessage().getMessageID() == messageID) { iter.remove(); ref = theRef; break; } } return ref; }
private void addMainSession(Session session) { InetSocketAddress remoteSocketAddress = session.getRemoteSocketAddress(); log.warn( "Add a session: " + SystemUtils.getRawAddress(remoteSocketAddress) + ":" + remoteSocketAddress.getPort()); Queue<Session> sessions = this.sessionMap.get(remoteSocketAddress); if (sessions == null) { sessions = new ConcurrentLinkedQueue<Session>(); Queue<Session> oldSessions = this.sessionMap.putIfAbsent(remoteSocketAddress, sessions); if (null != oldSessions) { sessions = oldSessions; } } // If it is in failure mode,remove closed session from list if (this.failureMode) { Iterator<Session> it = sessions.iterator(); while (it.hasNext()) { Session tmp = it.next(); if (tmp.isClosed()) { it.remove(); break; } } } sessions.offer(session); // Remove old session and close it while (sessions.size() > this.connectionPoolSize) { Session oldSession = sessions.poll(); ((MemcachedSession) oldSession).setAllowReconnect(false); oldSession.close(); } }
@NotNull private static Collection<CallableMemberDescriptor> extractMembersOverridableInBothWays( @NotNull CallableMemberDescriptor overrider, @NotNull Queue<CallableMemberDescriptor> extractFrom, @NotNull DescriptorSink sink) { Collection<CallableMemberDescriptor> overridable = new ArrayList<CallableMemberDescriptor>(); overridable.add(overrider); for (Iterator<CallableMemberDescriptor> iterator = extractFrom.iterator(); iterator.hasNext(); ) { CallableMemberDescriptor candidate = iterator.next(); if (overrider == candidate) { iterator.remove(); continue; } OverrideCompatibilityInfo.Result result1 = DEFAULT.isOverridableBy(candidate, overrider).getResult(); OverrideCompatibilityInfo.Result result2 = DEFAULT.isOverridableBy(overrider, candidate).getResult(); if (result1 == OVERRIDABLE && result2 == OVERRIDABLE) { overridable.add(candidate); iterator.remove(); } else if (result1 == CONFLICT || result2 == CONFLICT) { sink.conflict(overrider, candidate); iterator.remove(); } } return overridable; }
public void setNextPosition() { if (mMovableMaskQueue.size() == 0) return; Iterator<MovableMask> it = mMovableMaskQueue.iterator(); while (it.hasNext()) { MovableMask mask = it.next(); int x = mask.getCenterX(); int y = mask.getCenterY(); int step = mask.getStep(); int direction = mask.getDirection(); switch (direction) { case Utils.NORTH: Utils.log(TAG, "moving north"); mask.setCenter(x, y - step); break; case Utils.SOUTH: Utils.log(TAG, "moving south"); mask.setCenter(x, y + step); break; case Utils.WEST: Utils.log(TAG, "moving west"); mask.setCenter(x - step, y); break; case Utils.EAST: Utils.log(TAG, "moving east"); mask.setCenter(x + step, y); break; default: break; } // Utils.log(TAG, "get next position,x:" + x + ",y" + y); } }
protected void handleView(View view) { this.view = view; if (log.isDebugEnabled()) log.debug("view=" + view); List<Address> members = view.getMembers(); _consumerLock.lock(); try { // This removes the consumers that were registered that are now gone Iterator<Owner> iterator = _consumersAvailable.iterator(); while (iterator.hasNext()) { Owner owner = iterator.next(); if (!members.contains(owner.getAddress())) { iterator.remove(); sendRemoveConsumerRequest(owner); } } // This removes the tasks that those requestors are gone iterator = _runRequests.iterator(); while (iterator.hasNext()) { Owner owner = iterator.next(); if (!members.contains(owner.getAddress())) { iterator.remove(); sendRemoveRunRequest(owner); } } synchronized (_awaitingReturn) { for (Entry<Owner, Runnable> entry : _awaitingReturn.entrySet()) { // The person currently servicing our request has gone down // without completing so we have to keep our request alive by // sending ours back to the coordinator Owner owner = entry.getKey(); if (!members.contains(owner.getAddress())) { Runnable runnable = entry.getValue(); // We need to register the request id before sending the request back to the coordinator // in case if our task gets picked up since another was removed _requestId.put(runnable, owner.getRequestId()); _awaitingConsumer.add(runnable); sendToCoordinator(RUN_REQUEST, owner.getRequestId(), local_addr); } } } } finally { _consumerLock.unlock(); } }
@Override protected void execute(TaskListener listener) throws IOException { for (Iterator<PullRequestInstance> iter = terminatingInstances.iterator(); iter.hasNext(); ) { if (deleteInstance(iter.next(), listener)) { iter.remove(); } } }
public StreamsResultSet readRange(DateTime start, DateTime end) { LOGGER.debug("{} readRange", STREAMS_ID); this.start = start; this.end = end; readCurrent(); StreamsResultSet result = (StreamsResultSet) providerQueue.iterator(); return result; }
/** * Calculates the total weight of trucks currently on bridge * * @param None * @return totalWeight */ public int getTotalWeight() { int totalWeight = 0; Iterator<Truck> it = theBridgeQueue.iterator(); while (it.hasNext()) { totalWeight += it.next().getWeight(); } return totalWeight; }
public void generateBranches( World world, Random rand, int x, int y, int z, int height, double radius) { int branchCount = BRANCHES_BASE_NUMBER + rand.nextInt(BRANCHES_EXTRA); double curAngle = 0.0D; double[] average = {0, 0, 0}; int[] start = {x, y, z}; Queue<int[]> branches = new LinkedList<int[]>(); // Generate the branches for (int i = 0; i < branchCount; i++) { // Get the branch radius and height double angle = (rand.nextInt(50) + 35) / 90.0D; double thisHeight = (height + 1) * Math.sin(angle) / 1.3; double thisRadius = radius * Math.cos(angle); // Get the branch rotation curAngle += (rand.nextInt(360 / branchCount) + (360 / branchCount)) / 90.0D; // + (360.0D/branchCount) / 180.0D ; int x1 = (int) ((thisRadius) * Math.cos(curAngle)); int z1 = (int) ((thisRadius) * Math.sin(curAngle)); // Add the the average count average[0] += x1; average[1] += thisHeight; average[2] += z1; // Add to the branch list int[] node = new int[] {x1 + x, (int) thisHeight + y, z1 + z}; // Add the branch end for leaf generation branches.add(node); // Generate the branch placeBlockLine(start, node, TreeBlock.TRUNK.get(), world); } // Place the branch tips Iterator<int[]> itt = branches.iterator(); while (itt.hasNext()) { int[] cluster = itt.next(); generateLeafCluster(world, cluster[0], cluster[1], cluster[2], 2, 1, TreeBlock.LEAVES.get()); } // Calculate the center position average[0] /= branchCount; average[1] = (branchCount / average[1]) + 2.3D; average[2] /= branchCount; // Generate the canopy generateCanopy( world, rand, average[0] + x, y, average[2] + z, radius, height, TreeBlock.LEAVES.get()); // Generate the center cone generateVerticalCone(world, x, y, z, height - 1, .75, 2, TreeBlock.LEAVES.get()); }
public void printQueue() { Queue<Neighbor> copy = new PriorityQueue<Neighbor>(neighbors); Iterator<Neighbor> itr = copy.iterator(); System.out.println("SIZE: " + copy.size()); while (itr.hasNext()) { Neighbor n = copy.poll(); System.out.println(n.index + " - " + n.distance); } }
// Check if given node ID is in request queue private boolean elementInQueue(Queue que, int element) { Iterator iterator = que.iterator(); while (iterator.hasNext()) { int e = (int) iterator.next(); if (e == element) { return true; } } return false; }
/** * 删除ack对应的请求包 * * @param ack */ public synchronized void remove(InPacket ack) { for (Iterator<OutPacket> i = timeoutQueue.iterator(); i.hasNext(); ) { OutPacket packet = i.next(); if (ack.equals(packet)) { toPort.remove(packet); i.remove(); break; } } }
private void removeTerminatedClients() { Iterator<ISyncRequestClient> it = m_syncRequestClients.iterator(); while (it.hasNext()) { ISyncRequestClient client = it.next(); if (client.isTerminated()) { it.remove(); m_terminatedClients.add(client); } } }
/** Removes a listener for updated cluster states. */ public void remove(ClusterStateListener listener) { clusterStateListeners.remove(listener); priorityClusterStateListeners.remove(listener); lastClusterStateListeners.remove(listener); postAppliedListeners.remove(listener); for (Iterator<NotifyTimeout> it = onGoingTimeouts.iterator(); it.hasNext(); ) { NotifyTimeout timeout = it.next(); if (timeout.listener.equals(listener)) { timeout.cancel(); it.remove(); } } }
protected void processRegistrationQueue() { // add any elements in queue for (Iterator<Object[]> it = registrationQueue.iterator(); it.hasNext(); ) { Object[] args = it.next(); SelectableChannel ch = (SelectableChannel) args[0]; try { ch.register(selector, (Integer) args[1], args[2]); } catch (ClosedChannelException e) { e.printStackTrace(); } it.remove(); } }
/** * Este método tiene ocmo objetivo crear el modulo de persistencia de la fabrica. * * @return Retorna un elemento para persistir */ public Element persistir() { Element xmlElement = new Element("FabricaDeEnemigos"); xmlElement.setAttribute("Nivel", String.valueOf(this.NumeroNivel)); xmlElement.setAttribute("Cantidad_Enemigos", String.valueOf(this.Cantidad_Enemigos)); Iterator it = ColaEnemigos.iterator(); while (it.hasNext()) { xmlElement.addContent(((Enemigo) it.next()).persistir()); } return xmlElement; }
/** * 将一个等待中的任务从下等待队列中移除 * * @param downloadId */ protected synchronized void removeWaitQueueTask(int downloadId) { Iterator<FileDownloaderModel> iterator = mWaitQueue.iterator(); while (iterator.hasNext()) { FileDownloaderModel model = iterator.next(); if (model != null && model.getId() == downloadId) { try { iterator.remove(); } catch (Exception e) { ILogger.e(e); } return; } } }
public boolean isValidMovePrefix(Move otherMove) { Piece otherPiece = otherMove.getPiece(); if (otherPiece.getPieceColor() != piece.getPieceColor() || otherMove.getPieceColumn() != pieceColumn || otherMove.getPieceRow() != pieceRow) { return false; } Iterator<ChessboardPosition> it = steps.iterator(); for (ChessboardPosition cp : otherMove.getSteps()) { if (!it.hasNext() || !cp.equals(it.next())) { return false; } } return true; }
public void removeBookedTicket(String projectionId, Integer place) { deleterThread.interrupt(); Iterator<Ticket> iterator = ticketExpirationTimes.iterator(); while (iterator.hasNext()) { Ticket ticket = iterator.next(); if (ticket.getProjection().getId().equals(Long.parseLong(projectionId))) { if (ticket.getSeat() == place) { ticketExpirationTimes.remove(ticket); break; } } } deleterThread = new Thread(thread); deleterThread.start(); }
// this is called before session commit a local tx public void finishTx() throws Exception { MessageInfo lastMi = null; MessageInfo mi = null; Iterator<MessageInfo> iter = deliveringRefs.iterator(); while (iter.hasNext()) { mi = iter.next(); if (mi.isLocalAcked()) { iter.remove(); lastMi = mi; } } if (lastMi != null) { session.getCoreSession().acknowledge(nativeId, lastMi.nativeId); } }
public void rollbackTx(Set<Long> acked) throws Exception { MessageInfo lastMi = null; MessageInfo mi = null; Iterator<MessageInfo> iter = deliveringRefs.iterator(); while (iter.hasNext()) { mi = iter.next(); if (mi.isLocalAcked()) { acked.add(mi.nativeId); lastMi = mi; } } if (lastMi != null) { session.getCoreSession().acknowledge(nativeId, lastMi.nativeId); } }
public void renderScreen() { if (mMovableMaskQueue.size() == 0) { if (mMaskType == MOVABLE_MASK) { mScreenView.removeAllViews(); } return; } mScreenView.removeAllViews(); Iterator<MovableMask> it = mMovableMaskQueue.iterator(); while (it.hasNext()) { MovableMask mask = it.next(); Rect rect = mask.getRect(); mScreenView.addView(mask); mask.layout(rect.left, rect.top, rect.right, rect.bottom); } }
public void publishMessages() { Iterator<String> itr = serializedMessages.iterator(); while (itr.hasNext()) { String message = itr.next(); for (Session session : sessions) { session.push(key, message); } itr.remove(); } synchronized (this) { submittedForPublishing = false; if (!serializedMessages.isEmpty()) { submitForPublishing(); } } }
private void tearDown(String reason) { List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList(); sessionLock.lock(); try { if (session != null) { session = null; /* * Walk all requests, check if they have been executing * or cancelled and remove them from the queue. */ final Iterator<Request> it = requests.iterator(); while (it.hasNext()) { final Request r = it.next(); if (r.future.isUncancellable()) { futuresToCancel.add(r.future); it.remove(); } else if (r.future.isCancelled()) { // This just does some house-cleaning it.remove(); } } remoteDevice.onRemoteSessionDown(); } } finally { sessionLock.unlock(); } // Notify pending request futures outside of the sessionLock to avoid unnecessarily // blocking the caller. for (UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) { if (Strings.isNullOrEmpty(reason)) { future.set(createSessionDownRpcResult()); } else { future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason)); } } }
protected void replay(long windowId) { // This operator can partition itself dynamically. When that happens a file can be re-hashed // to a different partition than the previous one. In order to handle this, the partition loads // all the recovery data for a window and then processes only those files which would be hashed // to it in the current run. try { Map<Integer, Object> recoveryDataPerOperator = idempotentStorageManager.load(windowId); for (Object recovery : recoveryDataPerOperator.values()) { @SuppressWarnings("unchecked") LinkedList<RecoveryEntry> recoveryData = (LinkedList<RecoveryEntry>) recovery; for (RecoveryEntry recoveryEntry : recoveryData) { if (scanner.acceptFile(recoveryEntry.file)) { // The operator may have continued processing the same file in multiple windows. // So the recovery states of subsequent windows will have an entry for that file however // the offset changes. // In this case we continue reading from previously opened stream. if (currentFile == null || !(currentFile.equals(recoveryEntry.file) && offset == recoveryEntry.startOffset)) { if (inputStream != null) { closeFile(inputStream); } processedFiles.add(recoveryEntry.file); // removing the file from failed and unfinished queues and pending set Iterator<FailedFile> failedFileIterator = failedFiles.iterator(); while (failedFileIterator.hasNext()) { FailedFile ff = failedFileIterator.next(); if (ff.path.equals(recoveryEntry.file) && ff.offset == recoveryEntry.startOffset) { failedFileIterator.remove(); break; } } Iterator<FailedFile> unfinishedFileIterator = unfinishedFiles.iterator(); while (unfinishedFileIterator.hasNext()) { FailedFile ff = unfinishedFileIterator.next(); if (ff.path.equals(recoveryEntry.file) && ff.offset == recoveryEntry.startOffset) { unfinishedFileIterator.remove(); break; } } if (pendingFiles.contains(recoveryEntry.file)) { pendingFiles.remove(recoveryEntry.file); } inputStream = retryFailedFile(new FailedFile(recoveryEntry.file, recoveryEntry.startOffset)); while (offset < recoveryEntry.endOffset) { T line = readEntity(); offset++; emit(line); } } else { while (offset < recoveryEntry.endOffset) { T line = readEntity(); offset++; emit(line); } } } } } } catch (IOException e) { throw new RuntimeException("replay", e); } }