@Override public void refresh() { int tierfound = 2; Iterator<IConductor> it = this.conductors.iterator(); while (it.hasNext()) { IConductor conductor = it.next(); if (conductor == null) { it.remove(); continue; } TileEntity tile = (TileEntity) conductor; World world = tile.getWorldObj(); // Remove any conductors in unloaded chunks if (tile.isInvalid() || world == null) { it.remove(); continue; } if (conductor.getTierGC() < 2) { tierfound = 1; } if (conductor.getNetwork() != this) { conductor.setNetwork(this); conductor.onNetworkChanged(); } } // This will set the network tier to 2 if all the conductors are tier 2 this.networkTierGC = tierfound; }
protected Collection<TransactionOutputEx> getSpendableOutputs() { Collection<TransactionOutputEx> list = _backing.getAllUnspentOutputs(); // Prune confirmed outputs for coinbase outputs that are not old enough // for spending. Also prune unconfirmed receiving coins except for change int blockChainHeight = getBlockChainHeight(); Iterator<TransactionOutputEx> it = list.iterator(); while (it.hasNext()) { TransactionOutputEx output = it.next(); if (output.isCoinBase) { int confirmations = blockChainHeight - output.height; if (confirmations < COINBASE_MIN_CONFIRMATIONS) { it.remove(); continue; } } // Unless we allow zero confirmation spending we prune all unconfirmed outputs sent from // foreign addresses if (!_allowZeroConfSpending) { if (output.height == -1 && !isFromMe(output.outPoint.hash)) { // Prune receiving coins that is not change sent to ourselves it.remove(); } } } return list; }
private void analyzeEdges(UniversalGraph<Node, Edge> graph, int colCount) { for (Node node : graph.getNodes()) { node.conLeft = false; node.conRight = false; node.conTop = false; node.conBottom = false; node.conLeftTop = 0; node.conLeftBottom = 0; node.conRightTop = 0; node.conRightBottom = 0; } int rowCount = coordinates.size(); ArrayList<Edge> edgesList = new ArrayList<Edge>(graph.getEdges()); for (int row = 0; row < rowCount; row++) { for (int jump = 0; jump < colCount - 1; jump++) { Iterator<Edge> edges = edgesList.iterator(); while (edges.hasNext()) { Edge edge = edges.next(); if (edge.forward() && edge.sameRow(row) && edge.jump() == jump) { analyzeEdge(row, jump, edge); edges.remove(); } } edges = edgesList.iterator(); while (edges.hasNext()) { Edge edge = edges.next(); if (edge.backward() && edge.sameRow(row) && edge.jump() == jump) { analyzeEdge(row, jump, edge); edges.remove(); } } } } }
@SuppressLint("WorldReadableFiles") @Override protected FilterResults performFiltering(CharSequence constraint) { // NOTE: this function is *always* called from a background thread, and // not the UI thread. ArrayList<ApplicationInfo> items = new ArrayList<ApplicationInfo>(); synchronized (this) { items.addAll(appList); } SharedPreferences prefs = getSharedPreferences(Common.PREFS, Context.MODE_WORLD_READABLE); FilterResults result = new FilterResults(); if (constraint != null && constraint.length() > 0) { Pattern regexp = Pattern.compile(constraint.toString(), Pattern.LITERAL | Pattern.CASE_INSENSITIVE); for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (!regexp.matcher(app.name == null ? "" : app.name).find() && !regexp.matcher(app.packageName).find()) { i.remove(); } } } for (Iterator<ApplicationInfo> i = items.iterator(); i.hasNext(); ) { ApplicationInfo app = i.next(); if (filteredOut(prefs, app)) i.remove(); } result.values = items; result.count = items.size(); return result; }
private IName[] findDefinitions( IIndex index, IASTTranslationUnit ast, NameKind kind, IBinding binding) throws CoreException { List<IASTName> declNames = new ArrayList<IASTName>(); declNames.addAll(Arrays.asList(ast.getDefinitionsInAST(binding))); for (Iterator<IASTName> i = declNames.iterator(); i.hasNext(); ) { IASTName name = i.next(); final IBinding b2 = name.resolveBinding(); if (b2 instanceof ICPPUsingDeclaration) { i.remove(); } if (binding != b2 && binding instanceof ICPPSpecialization) { // Make sure binding specializes b2 so that for instance we do not navigate from // one partial specialization to another. IBinding spec = binding; while (spec instanceof ICPPSpecialization) { spec = ((ICPPSpecialization) spec).getSpecializedBinding(); if (spec == b2) break; } if (!(spec instanceof ICPPSpecialization)) { i.remove(); } } } if (!declNames.isEmpty()) { return declNames.toArray(new IASTName[declNames.size()]); } // 2. Try definition in index. return index.findNames( binding, IIndex.FIND_DEFINITIONS | IIndex.SEARCH_ACROSS_LANGUAGE_BOUNDARIES); }
public void testArrayIterators() { assertIteration(new Integer[] {}); assertIteration(new Integer[] {new Integer(0)}); assertIteration(new Integer[] {new Integer(0), new Integer(1)}); assertIteration(new Integer[] {new Integer(0), new Integer(1), new Integer(2)}); assertIteration(new Integer[] {new Integer(0), new Integer(1), new Integer(2), new Integer(3)}); Object[] xs = new Object[] {"a", "b", "c"}; assertNotNull(xs[1]); Iterator it = new Iterators.Array(xs); it.next(); it.next(); it.remove(); assertNull(xs[1]); Object[] ys = new Object[] {"a"}; assertNotNull(ys[0]); it = new Iterators.Array(ys); boolean threw = false; try { it.remove(); } catch (IllegalStateException e) { threw = true; } assertTrue(threw); threw = false; it.next(); it.remove(); try { it.remove(); } catch (IllegalStateException e) { threw = true; } assertTrue(threw); }
/** * removeJobTasks: Cleanup mapTasks and reduceTasks for this job * * @param jobID */ private void removeJobTasks(int jobID) { System.out.println( communicator.getLocalHostName() + " proceeding to remove map tasks for job " + jobID); mapLock.lock(); Iterator<MapTask> itr = mapTasks.iterator(); while (itr.hasNext()) { MapTask task = itr.next(); if (task.getJobConf().getJobID() == jobID) { itr.remove(); } } mapLock.unlock(); System.out.println( communicator.getLocalHostName() + " proceeding to remove reduce tasks for job " + jobID); reduceLock.lock(); Iterator<ReduceTask> itr1 = reduceTasks.iterator(); while (itr1.hasNext()) { ReduceTask task = itr1.next(); if (task.getJobConf().getJobID() == jobID) { itr1.remove(); } } reduceLock.unlock(); }
private Set<TypeElement> getTypeFromProperties(Set<TypeElement> parents) { Set<TypeElement> elements = new HashSet<TypeElement>(); for (Element element : parents) { if (element instanceof TypeElement) { processFromProperties((TypeElement) element, elements); } } Iterator<TypeElement> iterator = elements.iterator(); while (iterator.hasNext()) { TypeElement element = iterator.next(); String name = element.getQualifiedName().toString(); if (name.startsWith("java.") || name.startsWith("org.joda.time.")) { iterator.remove(); } else { boolean annotated = false; for (Class<? extends Annotation> annotation : conf.getEntityAnnotations()) { annotated |= element.getAnnotation(annotation) != null; } if (annotated) { iterator.remove(); } } } return elements; }
synchronized void reap() { currentKeysToClean.clear(); currentFullClean.clear(); for (Iterator<CleanupKey> iterator = keysToClean.iterator(); iterator.hasNext(); ) { CleanupKey cleanupKey = iterator.next(); iterator.remove(); if (cleanupKey.readerVersion == -1 || cleanupKey.indexShard.state() == IndexShardState.CLOSED) { // -1 indicates full cleanup, as does a closed shard currentFullClean.add(cleanupKey.indexShard); } else { currentKeysToClean.add(cleanupKey); } } if (!currentKeysToClean.isEmpty() || !currentFullClean.isEmpty()) { CleanupKey lookupKey = new CleanupKey(null, -1); for (Iterator<Key> iterator = cache.asMap().keySet().iterator(); iterator.hasNext(); ) { Key key = iterator.next(); if (currentFullClean.contains(key.shard)) { iterator.remove(); } else { lookupKey.indexShard = key.shard; lookupKey.readerVersion = key.readerVersion; if (currentKeysToClean.contains(lookupKey)) { iterator.remove(); } } } } cache.cleanUp(); currentKeysToClean.clear(); currentFullClean.clear(); }
/** * Try to execute all waiting processes. A process can be either executed, skipped or left * waiting, using the following rules: * * <ul> * <li>If the waiting process has incoming conditional parameters and one of these parameters is * not set, the process is skipped. * <li>If all of the parameters of the process are ready, execute the process. * </ul> */ private void tryToExecuteWaitingInstances() { final Set<OPMProcess> followingProcesses = Sets.newHashSet(); OPMInstanceExecutor instanceExecutor; for (final Iterator<OPMProcessInstance> waitingInstanceIt = waitingInstances.iterator(); waitingInstanceIt.hasNext(); ) { OPMProcessInstance waitingInstance = waitingInstanceIt.next(); instanceExecutor = new OPMInstanceExecutor(waitingInstance, this); instanceExecutor.tryToExecuteInstance(); if (instanceExecutor.wasNotExecuted()) { // do nothing } else if (instanceExecutor.wasSkipped()) { addSkippedProcess(instanceExecutor.getProcess()); followingProcesses.addAll(calculateFollowingProcesses(instanceExecutor)); waitingInstanceIt.remove(); } else { executingInstances.add(waitingInstance); waitingInstanceIt.remove(); } } putProcessesInWaitingList(followingProcesses); }
/** Eliminate below less frequency n-grams and noise Latin alphabets */ public void omitLessFreq() { if (getName() == null) return; // Illegal int threshold = getNWords()[0] / LESS_FREQ_RATIO; if (threshold < MINIMUM_FREQ) threshold = MINIMUM_FREQ; Set<String> keys = getFreq().keySet(); int roman = 0; for (Iterator<String> i = keys.iterator(); i.hasNext(); ) { String key = i.next(); int count = getFreq().get(key); if (count <= threshold) { getNWords()[key.length() - 1] -= count; i.remove(); } else { if (key.matches("^[A-Za-z]$")) { roman += count; } } } // roman check if (roman < getNWords()[0] / 3) { Set<String> keys2 = getFreq().keySet(); for (Iterator<String> i = keys2.iterator(); i.hasNext(); ) { String key = i.next(); if (key.matches(".*[A-Za-z].*")) { getNWords()[key.length() - 1] -= getFreq().get(key); i.remove(); } } } }
/** * Merges to user lists. New users will be added and old users will be updated. * * @param aOriginal Original {@link List} of {@link User}. * @param aChanges New {@link List} of {@link User} to merge into original list. * @return Merges {@link List} of {@link User}. */ public static List<User> merge(List<User> aOriginal, List<User> aChanges) { List<User> vUsers = new ArrayList<User>(); // delete original users not in changes, not manually added and without letters for (Iterator<User> vIterator = aOriginal.iterator(); vIterator.hasNext(); ) { User vUser = vIterator.next(); List<User> vUsersSelected = UserListUtils.selectUnique(aChanges, vUser.getName(), vUser.getBirthdate()); if (vUsersSelected.size() == 0 && !vUser.isManualAdded()) { User vUserDeleted = new User(vUser); vUsers.add(vUserDeleted.setName(null)); vIterator.remove(); } } // update and add user data List<User> vUnassignedUsers = new ArrayList<User>(); // list of users with more unique // users in original list for (Iterator<User> vIterator = aChanges.iterator(); vIterator.hasNext(); ) { User vUser = vIterator.next(); List<User> vUsersSelected = UserListUtils.selectUnique(aOriginal, vUser.getName(), vUser.getBirthdate()); if (vUsersSelected.size() == 1) { // one unique user found > update user User vUserSelected = new User(vUsersSelected.get(0)).update(vUser); vUsers.add(vUserSelected); vIterator.remove(); } else if (vUsersSelected.size() == 0) { // no user found > check if to find without birthdate List<User> vUsersByName = UserListUtils.selectUnique(aOriginal, vUser.getName(), ""); if (vUsersByName.size() == 1) { // found user > update User vUserSelected = new User(vUsersByName.get(0)).update(vUser); vUsers.add(vUserSelected); } else { // not found by name > add user User vNewUser = new User(vUser); vUsers.add(vNewUser); vIterator.remove(); } } else if (vUnassignedUsers.size() > 1) { // more than one unique user found > add to list for further processing vUnassignedUsers.add(vUser); vIterator.remove(); } } // process unassigned users // TODO logger.warn("Unassigned users " + vUnassignedUsers.size()); return vUsers; }
/** Create fields for injections inside main class */ protected void generateFields() { for (Iterator<Element> iterator = mElements.iterator(); iterator.hasNext(); ) { Element element = iterator.next(); if (!element.used) { iterator.remove(); continue; } // remove duplicate field PsiField[] fields = mClass.getFields(); boolean duplicateField = false; for (PsiField field : fields) { String name = field.getName(); if (name != null && name.equals(element.getFieldName())) { duplicateField = true; break; } } if (duplicateField) { iterator.remove(); continue; } mClass.add( mFactory.createFieldFromText( "private " + element.name + " " + element.getFieldName() + ";", mClass)); } }
public void update() { Iterator<MovableObject> movableObjectsIter = this.movableObjects.iterator(); while (movableObjectsIter.hasNext()) { MovableObject obj = movableObjectsIter.next(); obj.update(); if (!obj.isAlive()) { movableObjectsIter.remove(); } } Iterator<MapObject> staticObjectsIter = this.staticObjects.iterator(); while (staticObjectsIter.hasNext()) { MapObject obj = staticObjectsIter.next(); obj.update(); if (!obj.isAlive()) { staticObjectsIter.remove(); } } flushNewItems(); }
private synchronized void closeStaleConnections() { // close idle connections Iterator<Connection> iter = availableConnections.iterator(); while (iter.hasNext()) { Connection existingConnection = iter.next(); if (isConnectionStale(existingConnection)) { try { existingConnection.close(); iter.remove(); } catch (SQLException sql) { logger.error(sql.getMessage(), sql); } } } // close busy connections that have been checked out for too long. // This should not happen since this means program has bug for not // releasing connections . iter = busyConnections.iterator(); while (iter.hasNext()) { Connection busyConnection = iter.next(); if (isConnectionStale(busyConnection)) { try { busyConnection.close(); iter.remove(); logger.warn( "****Connection has checked out too long. Forced release. Check the program for calling release connection [free(Connection) method]"); } catch (SQLException sql) { logger.error(sql.getMessage(), sql); } } } }
private void checkIfNeedHeartBeat( LinkedList<BackendConnection> heartBeatCons, ConQueue queue, ConcurrentLinkedQueue<BackendConnection> checkLis, long hearBeatTime, long hearBeatTime2) { int MAX_CONS_IN_ONE_CHECK = 10; Iterator<BackendConnection> checkListItor = checkLis.iterator(); while (checkListItor.hasNext()) { BackendConnection con = checkListItor.next(); if (con.isClosed()) { checkListItor.remove(); continue; } if (validSchema(con.getSchema())) { if (con.getLastTime() < hearBeatTime) { if (heartBeatCons.size() < MAX_CONS_IN_ONE_CHECK) { checkListItor.remove(); // Heart beat check con.setBorrowed(true); heartBeatCons.add(con); } } } else if (con.getLastTime() < hearBeatTime2) { { // not valid schema conntion should close for idle // exceed 2*conHeartBeatPeriod checkListItor.remove(); con.close(" heart beate idle "); } } } }
@Override public void act(float delta) { super.act(delta); if (TimeUtils.nanoTime() - lastCarTime > 3000000000f) spawnCar(); Iterator<EnemyCar> iter = enemyCars.iterator(); while (iter.hasNext()) { EnemyCar enemyCar = iter.next(); if (enemyCar.getBounds().x + enemyCar.getWidth() <= 0) { iter.remove(); removeActor(enemyCar); } if (enemyCar.getBounds().overlaps(playerCar.getBounds())) { iter.remove(); if (enemyCar.getX() > playerCar.getX()) { if (enemyCar.getY() > playerCar.getY()) enemyCar.crash(true, true); else enemyCar.crash(true, false); } else { if (enemyCar.getY() > playerCar.getY()) enemyCar.crash(false, true); else enemyCar.crash(false, false); } } } }
public static List<Portlet> getAlwaysExportablePortlets(long companyId) throws Exception { List<Portlet> portlets = PortletLocalServiceUtil.getPortlets(companyId); Iterator<Portlet> itr = portlets.iterator(); while (itr.hasNext()) { Portlet portlet = itr.next(); if (!portlet.isActive()) { itr.remove(); continue; } PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance(); if ((portletDataHandler == null) || !portletDataHandler.isAlwaysExportable()) { itr.remove(); } } return portlets; }
/** This function is called to refresh all conductors in this network */ @Override public void refresh() { this.oxygenTiles.clear(); try { Iterator<ITransmitter> it = this.pipes.iterator(); while (it.hasNext()) { ITransmitter transmitter = it.next(); if (transmitter == null) { it.remove(); continue; } transmitter.onNetworkChanged(); if (((TileEntity) transmitter).isInvalid() || ((TileEntity) transmitter).getWorldObj() == null) { it.remove(); continue; } else { transmitter.setNetwork(this); } } } catch (Exception e) { FMLLog.severe("Failed to refresh oxygen pipe network."); e.printStackTrace(); } }
@Override public void update(double t) { { // UPDATE TOWERS for (Tile[] tiles : getTiles()) for (Tile tile : tiles) if (tile.hasTower()) tile.getTower().update(t); } { // UPDATE BULLETS final Iterator<Bullet> it = getBullets().iterator(); while (it.hasNext()) { final Bullet b = it.next(); if (b.update(t)) it.remove(); } } { // UPDATE MOBS final Iterator<Mob> it = getMobs().iterator(); while (it.hasNext()) { final Mob m = it.next(); m.update(t); if (m.shouldBeRemoved()) { m.onRemove(getGame()); it.remove(); } } } }
/** * Clears away any URNs for files that do not exist anymore. * @param shouldClearURNSetMap true if you want to clear TIME_TO_URNSET_MAP * too */ private void pruneTimes(boolean shouldClearURNSetMap) { // if i'm using FM, always grab that lock first and then me. be quick // about it though :) synchronized (RouterService.getFileManager()) { synchronized (this) { Iterator iter = URN_TO_TIME_MAP.entrySet().iterator(); while (iter.hasNext()) { Map.Entry currEntry = (Map.Entry) iter.next(); if(!(currEntry.getKey() instanceof URN) || !(currEntry.getValue() instanceof Long)) { iter.remove(); dirty = true; continue; } URN currURN = (URN) currEntry.getKey(); Long cTime = (Long) currEntry.getValue(); // check to see if file still exists // NOTE: technically a URN can map to multiple FDs, but I only want // to know about one. getFileDescForUrn prefers FDs over iFDs. FileDesc fd = RouterService.getFileManager().getFileDescForUrn(currURN); if ((fd == null) || (fd.getFile() == null) || !fd.getFile().exists()) { dirty = true; iter.remove(); if (shouldClearURNSetMap) removeURNFromURNSet(currURN, cTime); } } } } }
@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; }
/** Checks all the servers marked as being online if they still are online. */ private synchronized void checkOnlineServers() { Iterator itr; itr = online.listIterator(); while (itr.hasNext()) { Server server = (Server) itr.next(); String url = getServerURL(server); GetMethod get = new GetMethod(url); get.setFollowRedirects(false); try { httpClient.executeMethod(get); if (!okServerResponse(get.getStatusCode())) { offline.add(server); itr.remove(); log.debug("Server going OFFLINE! " + getServerURL(server)); listener.serverOffline(server); } } catch (Exception e) { offline.add(server); itr.remove(); log.debug("Server going OFFLINE! " + getServerURL(server)); listener.serverOffline(server); } finally { get.releaseConnection(); } } }
@Override public void updateChunks(final long finishTimeNano) { this.displayListEntitiesDirty |= this.renderDispatcher.runChunkUploads(finishTimeNano); final Iterator<RenderChunk> chunkIterator = this.chunksToUpdate.iterator(); while (chunkIterator.hasNext()) { final RenderChunk renderChunk = chunkIterator.next(); if (!this.renderDispatcher.updateChunkLater(renderChunk)) { break; } renderChunk.setNeedsUpdate(false); chunkIterator.remove(); } this.displayListEntitiesDirty |= this.renderDispatcherOverlay.runChunkUploads(finishTimeNano); final Iterator<RenderOverlay> overlayIterator = this.overlaysToUpdate.iterator(); while (overlayIterator.hasNext()) { final RenderOverlay renderOverlay = overlayIterator.next(); if (!this.renderDispatcherOverlay.updateChunkLater(renderOverlay)) { break; } renderOverlay.setNeedsUpdate(false); overlayIterator.remove(); } }
/** {@inheritDoc} */ public void applyFederationFilter(final Collection list, final Class objectType) { final Set<Long> manageableShopIds = shopFederationStrategy.getAccessibleShopIdsByCurrentManager(); final Iterator<CarrierDTO> carriersIt = list.iterator(); while (carriersIt.hasNext()) { final CarrierDTO carrier = carriersIt.next(); try { final Map<ShopDTO, Boolean> shops = carrierService.getAssignedCarrierShops(carrier.getCarrierId()); boolean manageable = false; for (final ShopDTO shop : shops.keySet()) { if (manageableShopIds.contains(shop.getShopId())) { manageable = true; break; } } if (!manageable) { carriersIt.remove(); } } catch (Exception exp) { carriersIt.remove(); } } }
private void processFragments(Object f, boolean last) { synchronized (fragments) { fragments.add(f); if (last) { if (f instanceof String) { // string StringBuilder sb = new StringBuilder(); for (Iterator<Object> it = fragments.iterator(); it.hasNext(); ) { Object o = it.next(); if (o instanceof String) { sb.append((String) o); it.remove(); } } received.add(sb.toString()); } else { // byte[] ByteArrayOutputStream bao = new ByteArrayOutputStream(); for (Iterator<Object> it = fragments.iterator(); it.hasNext(); ) { Object o = it.next(); if (o instanceof byte[]) { bao.write((byte[]) o, 0, ((byte[]) o).length); it.remove(); } } received.add(bao.toByteArray()); } } } }
public void secondPhase() { int count = _ways.values().size(); // This copies relevant tags to the ways (highway=*) where it doesn't exist, so that // the way purging keeps the needed way around. // Multipolygons may be processed more than once, which may be needed since // some member might be in different files for the same multipolygon. processMultipolygons(); for (Iterator<OSMWay> it = _ways.values().iterator(); it.hasNext(); ) { OSMWay way = it.next(); if (!(way.hasTag("highway") || way.isTag("railway", "platform"))) { it.remove(); } else if (way.isTag("highway", "conveyer") || way.isTag("highway", "proposed")) { it.remove(); } else { // Since the way is kept, update nodes-with-neighbors List<Long> nodes = way.getNodeRefs(); if (nodes.size() > 1) { _nodesWithNeighbors.addAll(nodes); } } } _log.trace("purged " + (count - _ways.values().size()) + " ways out of " + count); }
/** @param line */ public ExecJavaCliParser(String line) { this.optionParser = new OptionParser("D:X:"); this.optionParser.allowsUnrecognizedOptions(); this.xVmOptions = this.optionParser.accepts("X").withRequiredArg(); this.sysPropOptions = this.optionParser.accepts("D").withRequiredArg(); this.mainArgumentsOptions = this.optionParser.nonOptions(); this.optionSet = this.optionParser.parse(line.split(" ")); Pattern p = Pattern.compile("([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*"); this.mainArguments = new ArrayList<String>(this.mainArgumentsOptions.values(this.optionSet)); Iterator<String> mainArgumentsIter = this.mainArguments.iterator(); boolean mainFound = false; while (mainArgumentsIter.hasNext()) { String value = mainArgumentsIter.next(); Matcher m = p.matcher(value); boolean matches = m.matches(); if (matches && !mainFound) { mainFound = true; this.main = value; mainArgumentsIter.remove(); break; } else if (!mainFound) { mainArgumentsIter.remove(); } } }
/** * Given a new LimitOrder, it will replace and old matching limit order in the orderbook or simply * get added. Finally, it is sorted. * * @param limitOrder */ public void update(LimitOrder limitOrder) { if (limitOrder.getType().equals(OrderType.ASK)) { Iterator<LimitOrder> it = asks.iterator(); while (it.hasNext()) { LimitOrder order = it.next(); if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice()) == 0) { // they are equal. found it! it.remove(); break; } } asks.add(limitOrder); // just add it Collections.sort(asks); // finally sort } else { Iterator<LimitOrder> it = bids.iterator(); while (it.hasNext()) { LimitOrder order = it.next(); if (order.getLimitPrice().compareTo(limitOrder.getLimitPrice()) == 0) { // they are equal. found it! it.remove(); break; } } bids.add(limitOrder); // just add it Collections.sort(bids); // finally sort } }
final synchronized void deconnection(String id) { for (Iterator i = distantKernels.iterator(); i.hasNext(); ) { AgentAddress distantK = (AgentAddress) i.next(); if (distantK.getKernel().getID().equals(id)) { debug("disconnected from " + id); for (Iterator j = organizations.entrySet().iterator(); j.hasNext(); ) { Map.Entry e = (Map.Entry) j.next(); Organization org = (Organization) e.getValue(); if (org.removeAgentsFromKernel(distantK.getKernel())) { leaveGroup("communities", (String) e.getKey()); sendAll( new SynchroMessage( Kernel.LEAVE_GROUP, getAddress(), COMMUNITIES, (String) e.getKey(), null, null)); sendAll(new SynchroMessage(Kernel.DELETE_COMMUNITY, (String) e.getKey())); j.remove(); } } kernelAgent.callHooks(Kernel.DISCONNECTED_FROM, distantK.getKernel()); kernelAgent.callHooks(Kernel.REMOVE_MEMBER_ROLE, distantK, COMMUNITIES, PUBLIC, SITE); i.remove(); System.gc(); System.runFinalization(); break; } } if (gui != null) gui.refreshCommunities(); }