List of usage examples for java.util ListIterator hasNext
boolean hasNext();
From source file:org.apache.solr.handler.component.HttpShardHandler.java
/** * A distributed request is made via {@link LBHttpSolrClient} to the first live server in the URL list. * This means it is just as likely to choose current host as any of the other hosts. * This function makes sure that the cores of current host are always put first in the URL list. * If all nodes prefer local-cores then a bad/heavily-loaded node will receive less requests from healthy nodes. * This will help prevent a distributed deadlock or timeouts in all the healthy nodes due to one bad node. *//*from ww w .j a va 2 s. co m*/ private void preferCurrentHostForDistributedReq(final String currentHostAddress, final List<String> urls) { if (log.isDebugEnabled()) log.debug("Trying to prefer local shard on {} among the urls: {}", currentHostAddress, Arrays.toString(urls.toArray())); ListIterator<String> itr = urls.listIterator(); while (itr.hasNext()) { String url = itr.next(); if (url.startsWith(currentHostAddress)) { // move current URL to the fore-front itr.remove(); urls.add(0, url); if (log.isDebugEnabled()) log.debug("Applied local shard preference for urls: {}", Arrays.toString(urls.toArray())); break; } } }
From source file:com.manydesigns.portofino.dispatcher.Dispatcher.java
protected void makePageInstancePath(List<PageInstance> pagePath, ListIterator<String> fragmentsIterator) throws Exception { PageInstance parentPageInstance = pagePath.get(pagePath.size() - 1); File currentDirectory = parentPageInstance.getChildrenDirectory(); boolean params = !parentPageInstance.getParameters().isEmpty(); while (fragmentsIterator.hasNext()) { String nextFragment = fragmentsIterator.next(); File childDirectory = new File(currentDirectory, nextFragment); if (childDirectory.isDirectory() && !PageInstance.DETAIL.equals(childDirectory.getName())) { ChildPage childPage = null;//from w ww.jav a 2 s. com for (ChildPage candidate : parentPageInstance.getLayout().getChildPages()) { if (candidate.getName().equals(childDirectory.getName())) { childPage = candidate; break; } } if (childPage == null) { throw new PageNotActiveException(); } Page page = DispatcherLogic.getPage(childDirectory); Class<? extends PageAction> actionClass = DispatcherLogic.getActionClass(configuration, childDirectory); PageInstance pageInstance = new PageInstance(parentPageInstance, childDirectory, page, actionClass); pagePath.add(pageInstance); makePageInstancePath(pagePath, fragmentsIterator); return; } else { if (!params) { currentDirectory = new File(currentDirectory, PageInstance.DETAIL); params = true; } parentPageInstance = parentPageInstance.copy(); parentPageInstance.getParameters().add(nextFragment); pagePath.set(pagePath.size() - 1, parentPageInstance); } } }
From source file:marytts.unitselection.analysis.ProsodyAnalyzer.java
/** * For debugging, generate Praat DurationTier, which can be used for PSOLA-based manipulation in Praat. * <p>/*from w w w .ja v a 2 s. com*/ * Notes: * <ul> * <li>Initial silence is skipped.</li> * <li>Units with zero realized duration are ignored.</li> * <li>To avoid gradual interpolation between points, place two points around each unit boundary, separated by * <code>MIN_SKIP</code>; this workaround allows one constant factor per unit.</li> * </ul> * * @param fileName * of the DurationTier to be generated * @throws IOException */ public void writePraatDurationTier(String fileName) throws IOException { // initialize times and values with a size corresponding to two elements (start and end) per unit: ArrayList<Double> times = new ArrayList<Double>(units.size() * 2); ArrayList<Double> values = new ArrayList<Double>(units.size() * 2); final double MIN_SKIP = 1e-15; // cumulative time pointer: double time = 0; // iterate over phones, skipping the initial silence: // TODO is this really robust? ListIterator<Phone> phoneIterator = phones.listIterator(1); while (phoneIterator.hasNext()) { Phone phone = phoneIterator.next(); // process left halfphone unit: if (phone.getLeftUnitDuration() > 0) { // add point at unit start: times.add(time); values.add(phone.getLeftDurationFactor()); // increment time pointer by unit duration: time += phone.getLeftUnitDuration(); // add point at unit end: times.add(time - MIN_SKIP); values.add(phone.getLeftDurationFactor()); } // process right halfphone unit: if (phone.getRightUnitDuration() > 0) { // add point at unit start: times.add(time); values.add(phone.getRightDurationFactor()); // increment time pointer by unit duration: time += phone.getRightUnitDuration(); // add point at unit end: times.add(time - MIN_SKIP); values.add(phone.getRightDurationFactor()); } } // open file for writing: File durationTierFile = new File(fileName); PrintWriter out = new PrintWriter(durationTierFile); // print header: out.println("\"ooTextFile\""); out.println("\"DurationTier\""); out.println(String.format("0 %f %d", time, times.size())); // print points (times and values): for (int i = 0; i < times.size(); i++) { // Note: time precision should be greater than MIN_SKIP: out.println(String.format("%.16f %f", times.get(i), values.get(i))); } // flush and close: out.close(); }
From source file:edu.oregonstate.eecs.mcplan.sim.OptionSimulator.java
@Override public void takeAction(final JointAction<Option<S, A>> j) { action_count_ += 1;/*from w w w. jav a2 s . co m*/ // System.out.println( "Setting option " + o + " for player " + turn_ ); // Find all options that terminated final ArrayList<Option<S, A>> term = new ArrayList<Option<S, A>>(); for (int i = 0; i < turn_.size(); ++i) { assert (active_.get(i) == null); term.add(terminated_.get(i)); terminated_.set(i, null); } pushFrame(turn_, term); // Activate new options for (int i = 0; i < turn_.size(); ++i) { assert (j.get(i) != null); final Option<S, A> o = j.get(i); active_.set(i, o); o.start(base_.state(), base_.t()); } assert (history_.size() == action_count_); // TODO: Debugging // Take actions according to active options until one or more // options terminates. final long told = base_.t(); final long tnew = told; while (true) { final S s = base_.state(); if (base_.isTerminalState()) { return; } // See if any options terminate final ListIterator<Option<S, A>> check_itr = active_.listIterator(); final TIntArrayList next_turn = new TIntArrayList(); while (check_itr.hasNext()) { final Option<S, A> ocheck = check_itr.next(); if (terminate(s, base_.t(), ocheck)) { // System.out.println( "! Option " + (check_itr.previousIndex()) + " terminated" ); check_itr.set(null); final int pidx = check_itr.previousIndex(); terminated_.set(pidx, ocheck); next_turn.add(pidx); } } // If they do, wait for new options if (!next_turn.isEmpty()) { turn_ = next_turn; return; } // Construct a JointAction over primitive actions and execute it final JointAction.Builder<A> ab = new JointAction.Builder<A>(Nplayers_); for (int i = 0; i < Nplayers_; ++i) { final Option<S, A> o = active_.get(i); assert (o != null); o.setState(s, base_.t()); ab.a(i, o.getAction()); } base_.takeAction(ab.finish()); // System.out.println( "Take action " + base_.getTurn() + " " + a ); history_.peek().steps += 1; // TODO: Give pi its reward // pi.actionResult( ??? ); } }
From source file:io.bibleget.BibleGetFrame.java
/** * * @throws ClassNotFoundException// ww w . j a v a 2 s. c o m */ private void prepareDynamicInformation() throws ClassNotFoundException { biblegetDB = BibleGetDB.getInstance(); String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS"); JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr)); JsonObject bibleVersionsObj = jsonReader.readObject(); Set<String> versionsabbrev = bibleVersionsObj.keySet(); bibleVersions = new BasicEventList<>(); if (!versionsabbrev.isEmpty()) { for (String s : versionsabbrev) { String versionStr = bibleVersionsObj.getString(s); //store these in an array String[] array; array = versionStr.split("\\|"); bibleVersions.add(new BibleVersion(s, array[0], array[1], StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage()))); } } List<String> preferredVersions = new ArrayList<>(); String retVal = (String) biblegetDB.getOption("PREFERREDVERSIONS"); if (null == retVal) { //System.out.println("Attempt to retrieve PREFERREDVERSIONS from the Database resulted in null value"); } else { //System.out.println("Retrieved PREFERREDVERSIONS from the Database. Value is:"+retVal); String[] favoriteVersions = StringUtils.split(retVal, ','); preferredVersions = Arrays.asList(favoriteVersions); } if (preferredVersions.isEmpty()) { preferredVersions.add("NVBSE"); } List<Integer> preferredVersionsIndices = new ArrayList<>(); versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000); int listLength = versionsByLang.size(); enabledFlags = new boolean[listLength]; ListIterator itr = versionsByLang.listIterator(); while (itr.hasNext()) { int idx = itr.nextIndex(); Object next = itr.next(); enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator")); if (next.getClass().getSimpleName().equals("BibleVersion")) { BibleVersion thisBibleVersion = (BibleVersion) next; if (preferredVersions.contains(thisBibleVersion.getAbbrev())) { preferredVersionsIndices.add(idx); } } } indices = ArrayUtils .toPrimitive(preferredVersionsIndices.toArray(new Integer[preferredVersionsIndices.size()])); //System.out.println("value of indices array: "+Arrays.toString(indices)); }
From source file:com.vizury.videocache.product.ProductDetail.java
private ProductDetail[] getProductDataFromList(CacheConnect cache, String productList, HashMap<String, ProductDetail> recommendedProductDetail, int numberOfRecommendedProducts) { String[] productIdArray = productList.replace("\"", "").split(","); List<ProductDetail> productDetailList = new ArrayList<>(); List<ProductDetail> requestProductDetailList = new ArrayList<>(); for (String pid : productIdArray) { if (!pid.equals(productId)) { if (!recommendedProductDetail.containsKey(namespace + "_1_" + pid)) { requestProductDetailList.add(new ProductDetail(pid, namespace)); }/*from ww w . j a va 2 s . co m*/ productDetailList.add(new ProductDetail(pid, namespace)); } } Map<String, Object> productDetailMap = cache.getBulk(requestProductDetailList, "_1_"); if (productDetailMap != null) { ListIterator iterator = productDetailList.listIterator(); while (iterator.hasNext()) { ProductDetail productDetail = (ProductDetail) iterator.next(); if (productDetailMap.containsKey(namespace + "_1_" + productDetail.getProductId())) { productDetail.jsonToProductDetail( (String) productDetailMap.get(namespace + "_1_" + productDetail.getProductId())); recommendedProductDetail.put(namespace + "_1_" + productDetail.getProductId(), productDetail); } else { iterator.set(recommendedProductDetail.get(namespace + "_1_" + productDetail.getProductId())); } } } else { return null; } if (productDetailList.size() <= numberOfRecommendedProducts) { return productDetailList.toArray(new ProductDetail[productDetailList.size()]); } else { Random rand = new Random(); int randomIndex; int index; ProductDetail[] productDetail = new ProductDetail[numberOfRecommendedProducts]; for (index = 0; index < numberOfRecommendedProducts; index++) { randomIndex = rand.nextInt(productDetailList.size()); productDetail[index] = productDetailList.get(randomIndex); productDetailList.remove(randomIndex); } return productDetail; } }
From source file:com.projity.script.object.TimeIntervals.java
public TimeIntervals translate(int winCount) { //TODO case winCount<0 // for (TimeWindow w : history) System.out.println("history0: "+w); // for (TimeWindow w : win) System.out.println("win0: "+w); //for (TimeWindow w : history) System.out.println("id="+w.getId()); TimeIntervals t = new TimeIntervals(); t.setScale(scale);/*from w ww . ja va 2s. co m*/ LinkedList<TimeWindow> twin = t.getWin(); if (winCount == 0 || win.size() == 0) return t; //or null if (winCount > 0) { t.winId = winId + win.size(); int lastId = t.winId - 1 + winCount; int maxHistoryId = Math.min(history.getLast().getId(), lastId); int i = t.winId; if (i <= maxHistoryId) { ListIterator<TimeWindow> it = history.listIterator(); TimeWindow w; while (it.hasNext()) { w = it.next(); if (w.getId() == t.winId) { it.previous(); break; } } for (; i <= maxHistoryId && it.hasNext(); i++) { w = it.next(); twin.add(w); // System.out.println("Found in history: "+w); } } LinkedList<TimeWindow> newWin = new LinkedList<TimeWindow>(); generateWindows(scale, (twin.size() > 0 ? twin : win).getLast().getE(), start, end, lastId - i + 1, newWin); t.indexWindows(t.winId + t.getWin().size(), newWin); // for (TimeWindow w : newWin) System.out.println("New window: "+w); t.getWin().addAll(newWin); history.addAll(newWin); } else { t.winId = winId - 1; int lastId = t.winId + 1 + winCount; int minHistoryId = Math.max(history.getFirst().getId(), lastId); int i = t.winId; if (i >= minHistoryId) { ListIterator<TimeWindow> it = history.listIterator(history.size() - 1); TimeWindow w; while (it.hasPrevious()) { w = it.previous(); if (w.getId() == t.winId) { it.next(); break; } } for (; i >= minHistoryId; i--) { w = it.previous(); twin.addFirst(w); // System.out.println("Found in history: "+w); } } // System.out.println("winId="+winId+", t.winId="+t.winId+", lastId="+lastId+", i="+i+" minHistoryId="+minHistoryId); LinkedList<TimeWindow> newWin = new LinkedList<TimeWindow>(); generateWindows(scale, (twin.size() > 0 ? twin : win).getFirst().getS(), start, end, lastId - i - 1, newWin); t.indexWindows(lastId, newWin); // for (TimeWindow w : newWin) System.out.println("New window: "+w); t.getWin().addAll(0, newWin); history.addAll(0, newWin); } int translation = 0; for (TimeWindow w : t.getWin()) { if (winCount > 0) { win.removeFirst(); win.addLast(w); translation++; } else { win.removeLast(); win.addFirst(w); translation--; } } winId = winId + translation; t.setTranslation(translation); // for (TimeWindow w : history) System.out.println("history1: "+w); // for (TimeWindow w : win) System.out.println("win1: "+w); // for (TimeWindow w : twin) System.out.println("t.win1: "+w); return t; }
From source file:org.gephi.statistics.plugin.GraphDistance.java
public void execute(HierarchicalGraph hgraph, AttributeModel attributeModel) { isCanceled = false;/* www . ja v a 2 s.co m*/ AttributeTable nodeTable = attributeModel.getNodeTable(); AttributeColumn eccentricityCol = nodeTable.getColumn(ECCENTRICITY); AttributeColumn closenessCol = nodeTable.getColumn(CLOSENESS); AttributeColumn betweenessCol = nodeTable.getColumn(BETWEENNESS); if (eccentricityCol == null) { eccentricityCol = nodeTable.addColumn(ECCENTRICITY, "Eccentricity", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0)); } if (closenessCol == null) { closenessCol = nodeTable.addColumn(CLOSENESS, "Closeness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0)); } if (betweenessCol == null) { betweenessCol = nodeTable.addColumn(BETWEENNESS, "Betweenness Centrality", AttributeType.DOUBLE, AttributeOrigin.COMPUTED, new Double(0)); } hgraph.readLock(); N = hgraph.getNodeCount(); betweenness = new double[N]; eccentricity = new double[N]; closeness = new double[N]; diameter = 0; avgDist = 0; shortestPaths = 0; radius = Integer.MAX_VALUE; HashMap<Node, Integer> indicies = new HashMap<Node, Integer>(); int index = 0; for (Node s : hgraph.getNodes()) { indicies.put(s, index); index++; } Progress.start(progress, hgraph.getNodeCount()); int count = 0; for (Node s : hgraph.getNodes()) { Stack<Node> S = new Stack<Node>(); LinkedList<Node>[] P = new LinkedList[N]; double[] theta = new double[N]; int[] d = new int[N]; for (int j = 0; j < N; j++) { P[j] = new LinkedList<Node>(); theta[j] = 0; d[j] = -1; } int s_index = indicies.get(s); theta[s_index] = 1; d[s_index] = 0; LinkedList<Node> Q = new LinkedList<Node>(); Q.addLast(s); while (!Q.isEmpty()) { Node v = Q.removeFirst(); S.push(v); int v_index = indicies.get(v); EdgeIterable edgeIter = null; if (isDirected) { edgeIter = ((HierarchicalDirectedGraph) hgraph).getOutEdgesAndMetaOutEdges(v); } else { edgeIter = hgraph.getEdgesAndMetaEdges(v); } for (Edge edge : edgeIter) { Node reachable = hgraph.getOpposite(v, edge); int r_index = indicies.get(reachable); if (d[r_index] < 0) { Q.addLast(reachable); d[r_index] = d[v_index] + 1; } if (d[r_index] == (d[v_index] + 1)) { theta[r_index] = theta[r_index] + theta[v_index]; P[r_index].addLast(v); } } } double reachable = 0; for (int i = 0; i < N; i++) { if (d[i] > 0) { avgDist += d[i]; eccentricity[s_index] = (int) Math.max(eccentricity[s_index], d[i]); closeness[s_index] += d[i]; diameter = Math.max(diameter, d[i]); reachable++; } } radius = (int) Math.min(eccentricity[s_index], radius); if (reachable != 0) { closeness[s_index] /= reachable; } shortestPaths += reachable; double[] delta = new double[N]; while (!S.empty()) { Node w = S.pop(); int w_index = indicies.get(w); ListIterator<Node> iter1 = P[w_index].listIterator(); while (iter1.hasNext()) { Node u = iter1.next(); int u_index = indicies.get(u); delta[u_index] += (theta[u_index] / theta[w_index]) * (1 + delta[w_index]); } if (w != s) { betweenness[w_index] += delta[w_index]; } } count++; if (isCanceled) { hgraph.readUnlockAll(); return; } Progress.progress(progress, count); } avgDist /= shortestPaths;//mN * (mN - 1.0f); for (Node s : hgraph.getNodes()) { AttributeRow row = (AttributeRow) s.getNodeData().getAttributes(); int s_index = indicies.get(s); if (!isDirected) { betweenness[s_index] /= 2; } if (isNormalized) { closeness[s_index] = (closeness[s_index] == 0) ? 0 : 1.0 / closeness[s_index]; betweenness[s_index] /= isDirected ? (N - 1) * (N - 2) : (N - 1) * (N - 2) / 2; } row.setValue(eccentricityCol, eccentricity[s_index]); row.setValue(closenessCol, closeness[s_index]); row.setValue(betweenessCol, betweenness[s_index]); } hgraph.readUnlock(); }
From source file:com.quigley.filesystem.FilesystemPath.java
public FilesystemPath simplify() { List<String> elementsCopy = new ArrayList<String>(elements); ListIterator<String> i = elementsCopy.listIterator(); boolean saw = false; while (i.hasNext()) { String value = i.next();/*from w w w . ja v a 2 s. co m*/ if (value.equals(".")) { i.remove(); } else if (value.equals("..")) { if (saw) { if (i.hasPrevious()) { i.remove(); i.previous(); i.remove(); } } } else { saw = true; } } FilesystemPath pathCopy = new FilesystemPath(elementsCopy); pathCopy.isAbsolute = isAbsolute; return pathCopy; }
From source file:vteaexploration.plottools.panels.XYChartPanel.java
public void roiCreated(ImagePlus ip) { //if(impoverlay.equals(ip)){ ImageGateOverlay.clear();/* w w w . j a v a 2 s . c o m*/ ArrayList<MicroObject> volumes = (ArrayList) plotValues.get(1); ListIterator<MicroObject> itr = volumes.listIterator(); while (itr.hasNext()) { MicroObject m = itr.next(); int[] c = new int[2]; c = m.getBoundsCenter(); if (ip.getRoi().contains(c[0], c[1])) { ImageGateOverlay.add(m); } //} } //System.out.println("PROFILING: XYChartPanel... image gate, found " + ImageGateOverlay.size() + " volumes in region"); //process(xValues,yValues,lValues,xValuesText,yValuesText,lValuesText); //System.out.println("PROFILING: XYChartPanel... image gate processed and updated."); notifiyUpdatePlotWindowListeners(); }