List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:de.codesourcery.jasm16.ast.ASTUtils.java
public static Iterator<ASTNode> createInOrderIterator(ASTNode node) { if (node == null) { throw new IllegalArgumentException("node must not be NULL"); }/*from w ww.ja v a 2 s . co m*/ final Stack<ASTNode> stack = new Stack<ASTNode>(); stack.push(node); return new Iterator<ASTNode>() { @Override public boolean hasNext() { return !stack.isEmpty(); } /* A (1) * |\ *(5) E B (2) * |\ *(4) D C (3) */ @Override public ASTNode next() { if (stack.isEmpty()) { throw new NoSuchElementException(); } ASTNode result = stack.pop(); final List<ASTNode> children = result.getChildren(); Collections.reverse(children); for (ASTNode child : children) { stack.push(child); } return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
From source file:org.apache.hadoop.hdfs.TestDFSStripedOutputStreamWithFailure.java
private static void getComb(int n, int k, Stack<Integer> stack, List<List<Integer>> res) { if (stack.size() == k) { List<Integer> list = new ArrayList<Integer>(stack); res.add(list);//from w w w .ja v a2s . com } else { int next = stack.empty() ? 0 : stack.peek() + 1; while (next < n) { stack.push(next); getComb(n, k, stack, res); next++; } } if (!stack.empty()) { stack.pop(); } }
From source file:com.ms.commons.test.math.expression.util.MathExpressionParseUtil.java
private static Stack<String> adjustExpressionStack(Stack<String> expressionStack) { if (expressionStack.size() <= 2) { return expressionStack; }// w ww .j a v a 2 s . c o m int lastOpPr = Integer.MAX_VALUE; int lowerPrOp = -1; for (int i = (expressionStack.size() - 1); i >= 0; i--) { String expr = expressionStack.get(i); if ((expr.length() == 1) && hasSeparators(expr)) { int opPr = ("*".equals(expr) || "/".equals(expr)) ? 2 : 1; if (opPr < lastOpPr) { lastOpPr = opPr; lowerPrOp = i; } } } if (lowerPrOp != -1) { Stack<String> tempStack = new Stack<String>(); int popCount = expressionStack.size() - lowerPrOp - 1; for (int i = 0; i < popCount; i++) { tempStack.push(expressionStack.pop()); } Collections.reverse(tempStack); expressionStack.push(StringUtils.join(tempStack, "")); } return expressionStack; }
From source file:com.espertech.esper.rowregex.EventRowRegexHelper.java
private static RegexNFAStrand recursiveBuildStatesInternal(RowRegexExprNode node, Map<String, ExprNode> variableDefinitions, Map<String, Pair<Integer, Boolean>> variableStreams, Stack<Integer> nodeNumStack) { if (node instanceof RowRegexExprNodeAlteration) { int nodeNum = 0; List<RegexNFAStateBase> cumulativeStartStates = new ArrayList<RegexNFAStateBase>(); List<RegexNFAStateBase> cumulativeStates = new ArrayList<RegexNFAStateBase>(); List<RegexNFAStateBase> cumulativeEndStates = new ArrayList<RegexNFAStateBase>(); boolean isPassthrough = false; for (RowRegexExprNode child : node.getChildNodes()) { nodeNumStack.push(nodeNum);/*from w w w . j a va2s .co m*/ RegexNFAStrand strand = recursiveBuildStatesInternal(child, variableDefinitions, variableStreams, nodeNumStack); nodeNumStack.pop(); cumulativeStartStates.addAll(strand.getStartStates()); cumulativeStates.addAll(strand.getAllStates()); cumulativeEndStates.addAll(strand.getEndStates()); if (strand.isPassthrough()) { isPassthrough = true; } nodeNum++; } return new RegexNFAStrand(cumulativeStartStates, cumulativeEndStates, cumulativeStates, isPassthrough); } else if (node instanceof RowRegexExprNodeConcatenation) { int nodeNum = 0; boolean isPassthrough = true; List<RegexNFAStateBase> cumulativeStates = new ArrayList<RegexNFAStateBase>(); RegexNFAStrand[] strands = new RegexNFAStrand[node.getChildNodes().size()]; for (RowRegexExprNode child : node.getChildNodes()) { nodeNumStack.push(nodeNum); strands[nodeNum] = recursiveBuildStatesInternal(child, variableDefinitions, variableStreams, nodeNumStack); nodeNumStack.pop(); cumulativeStates.addAll(strands[nodeNum].getAllStates()); if (!strands[nodeNum].isPassthrough()) { isPassthrough = false; } nodeNum++; } // determine start states: all states until the first non-passthrough start state List<RegexNFAStateBase> startStates = new ArrayList<RegexNFAStateBase>(); for (int i = 0; i < strands.length; i++) { startStates.addAll(strands[i].getStartStates()); if (!strands[i].isPassthrough()) { break; } } // determine end states: all states from the back until the last non-passthrough end state List<RegexNFAStateBase> endStates = new ArrayList<RegexNFAStateBase>(); for (int i = strands.length - 1; i >= 0; i--) { endStates.addAll(strands[i].getEndStates()); if (!strands[i].isPassthrough()) { break; } } // hook up the end state of each strand with the start states of each next strand for (int i = strands.length - 1; i >= 1; i--) { RegexNFAStrand current = strands[i]; for (int j = i - 1; j >= 0; j--) { RegexNFAStrand prior = strands[j]; for (RegexNFAStateBase endState : prior.getEndStates()) { for (RegexNFAStateBase startState : current.getStartStates()) { endState.addState(startState); } } if (!prior.isPassthrough()) { break; } } } return new RegexNFAStrand(startStates, endStates, cumulativeStates, isPassthrough); } else if (node instanceof RowRegexExprNodeNested) { RowRegexExprNodeNested nested = (RowRegexExprNodeNested) node; nodeNumStack.push(0); RegexNFAStrand strand = recursiveBuildStatesInternal(node.getChildNodes().get(0), variableDefinitions, variableStreams, nodeNumStack); nodeNumStack.pop(); boolean isPassthrough = strand.isPassthrough() || nested.getType().isOptional(); // if this is a repeating node then pipe back each end state to each begin state if (nested.getType().isMultipleMatches()) { for (RegexNFAStateBase endstate : strand.getEndStates()) { for (RegexNFAStateBase startstate : strand.getStartStates()) { if (!endstate.getNextStates().contains(startstate)) { endstate.getNextStates().add(startstate); } } } } return new RegexNFAStrand(strand.getStartStates(), strand.getEndStates(), strand.getAllStates(), isPassthrough); } else { RowRegexExprNodeAtom atom = (RowRegexExprNodeAtom) node; // assign stream number for single-variables for most direct expression eval; multiple-variable gets -1 int streamNum = variableStreams.get(atom.getTag()).getFirst(); boolean multiple = variableStreams.get(atom.getTag()).getSecond(); ExprNode expressionDef = variableDefinitions.get(atom.getTag()); RegexNFAStateBase nextState; if ((atom.getType() == RegexNFATypeEnum.ZERO_TO_MANY) || (atom.getType() == RegexNFATypeEnum.ZERO_TO_MANY_RELUCTANT)) { nextState = new RegexNFAStateZeroToMany(toString(nodeNumStack), atom.getTag(), streamNum, multiple, atom.getType().isGreedy(), expressionDef); } else if ((atom.getType() == RegexNFATypeEnum.ONE_TO_MANY) || (atom.getType() == RegexNFATypeEnum.ONE_TO_MANY_RELUCTANT)) { nextState = new RegexNFAStateOneToMany(toString(nodeNumStack), atom.getTag(), streamNum, multiple, atom.getType().isGreedy(), expressionDef); } else if ((atom.getType() == RegexNFATypeEnum.ONE_OPTIONAL) || (atom.getType() == RegexNFATypeEnum.ONE_OPTIONAL_RELUCTANT)) { nextState = new RegexNFAStateOneOptional(toString(nodeNumStack), atom.getTag(), streamNum, multiple, atom.getType().isGreedy(), expressionDef); } else if (expressionDef == null) { nextState = new RegexNFAStateAnyOne(toString(nodeNumStack), atom.getTag(), streamNum, multiple); } else { nextState = new RegexNFAStateFilter(toString(nodeNumStack), atom.getTag(), streamNum, multiple, expressionDef); } return new RegexNFAStrand(Collections.singletonList(nextState), Collections.singletonList(nextState), Collections.singletonList(nextState), atom.getType().isOptional()); } }
From source file:net.leegorous.jsc.JavaScriptCombiner.java
public static String translate2RelatePath(File standard, File file) throws IOException { if (standard.isFile()) standard = standard.getParentFile(); String standardPath = standard.getCanonicalPath().replaceAll("\\\\", "/"); File target = file;/* w ww. ja v a 2s . c om*/ Stack stack = new Stack(); if (file.isFile()) { stack.push(target.getName()); target = file.getParentFile(); } String targetPath = file.getCanonicalPath().replaceAll("\\\\", "/"); StringBuffer result = new StringBuffer(); while (!targetPath.startsWith(standardPath)) { standardPath = standardPath.substring(0, standardPath.lastIndexOf("/")); result.append("../"); } while (!standardPath.equals(target.getCanonicalPath().replaceAll("\\\\", "/"))) { stack.push(target.getName()); target = target.getParentFile(); } while (stack.size() > 1) { result.append((String) stack.pop()).append("/"); } if (stack.size() > 0) result.append((String) stack.pop()); // System.out.println(standardPath+"\n"+targetPath); return result.toString(); }
From source file:com.runwaysdk.generation.loader.RunwayClassLoader.java
/** * Loads an array from the base component up. If an array is loaded without * its componentType already loaded then an error occurs. Thus it loads from * inside out.//from w w w. j av a 2s.c o m * * @param arrayType */ public static Class<?> loadArray(String arrayType) { // Keep track of what types of array we have (an array of Integers and an // array of // Business objects, for example) Stack<String> baseTypes = new Stack<String>(); String baseType = arrayType; Class<?> arrayClass = null; // This loop strips the base type out of any n-dimensional array while (arrayPattern.matcher(baseType).matches()) { if (arrayPrefix.matcher(baseType).matches()) { baseType = baseType.replaceFirst("\\[L", "").replace(";", "").trim(); } else { baseType = baseType.replaceFirst("\\[", ""); } // Add the base type to the stack baseTypes.push(baseType); } // We must load all base types before we can try to load arrays of those // types while (!baseTypes.isEmpty()) { String type = baseTypes.pop(); Class<?> componentType; componentType = LoaderDecorator.load(type); arrayClass = Array.newInstance(componentType, 0).getClass(); } return arrayClass; }
From source file:com.unboundid.scim2.common.utils.Parser.java
/** * Close a grouping of filters enclosed by parenthesis. * * @param operators The stack of operators tokens. * @param output The stack of output tokens. * @param isAtTheEnd Whether the end of the filter string was reached. * @return The last operator encountered that signaled the end of the group. * @throws BadRequestException If the filter string could not be parsed. *//*from w w w . j av a 2s . c om*/ private static String closeGrouping(final Stack<String> operators, final Stack<Filter> output, final boolean isAtTheEnd) throws BadRequestException { String operator = null; String repeatingOperator = null; LinkedList<Filter> components = new LinkedList<Filter>(); // Iterate over the logical operators on the stack until either there are // no more operators or an opening parenthesis or not is found. while (!operators.isEmpty()) { operator = operators.pop(); if (operator.equals("(") || operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) { if (isAtTheEnd) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } break; } if (repeatingOperator == null) { repeatingOperator = operator; } if (!operator.equals(repeatingOperator)) { if (output.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } components.addFirst(output.pop()); if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) { output.push(Filter.and(components)); } else { output.push(Filter.or(components)); } components.clear(); repeatingOperator = operator; } if (output.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } components.addFirst(output.pop()); } if (repeatingOperator != null && !components.isEmpty()) { if (output.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } components.addFirst(output.pop()); if (repeatingOperator.equalsIgnoreCase(FilterType.AND.getStringValue())) { output.push(Filter.and(components)); } else { output.push(Filter.or(components)); } } return operator; }
From source file:com.microsoft.tfs.core.clients.framework.configuration.internal.ReportingFolderEntityUtils.java
public static String getFullItemPath(final ReportingFolderEntity folder) { Check.notNull(folder, "folder"); //$NON-NLS-1$ final Stack<String> path = new Stack<String>(); TFSEntity facet = folder;/* w w w. ja va 2s . com*/ /* Walk the parentage to build the path to this object */ while (facet != null) { if (facet instanceof ReportingFolderEntity) { final String itemPath = ((ReportingFolderEntity) facet).getItemPath(); if (itemPath != null && itemPath.length() > 0) { path.push(itemPath); } facet = ((ReportingFolderEntity) facet).getReferencedResource(); } else if (facet instanceof ReportingServerEntity) { /* Stop */ break; } else { log.warn(MessageFormat.format("Invalid type {0} along reporting folder dependency chain", //$NON-NLS-1$ facet.getClass().getCanonicalName())); break; } } // Construct the full item path. String fullItemPath = ""; //$NON-NLS-1$ while (path.size() > 0) { String pathSegment = path.pop(); pathSegment = pathSegment.trim(); while (pathSegment.startsWith("/") || pathSegment.startsWith("\\")) //$NON-NLS-1$ //$NON-NLS-2$ { pathSegment = pathSegment.substring(1); } fullItemPath = URIUtils.combinePaths(fullItemPath, pathSegment); } // Full item paths always start with a '/' if (fullItemPath.startsWith("/")) //$NON-NLS-1$ { return fullItemPath; } return "/" + fullItemPath; //$NON-NLS-1$ }
From source file:hudson.model.Items.java
/** * Computes the canonical full name of a relative path in an {@link ItemGroup} context, handling relative * positions ".." and "." as absolute path starting with "/". The resulting name is the item fullName from Jenkins * root./*from w ww .ja va2 s .c om*/ */ public static String getCanonicalName(ItemGroup context, String path) { String[] c = context.getFullName().split("/"); String[] p = path.split("/"); Stack<String> name = new Stack<String>(); for (int i = 0; i < c.length; i++) { if (i == 0 && c[i].equals("")) continue; name.push(c[i]); } for (int i = 0; i < p.length; i++) { if (i == 0 && p[i].equals("")) { // Absolute path starting with a "/" name.clear(); continue; } if (p[i].equals("..")) { if (name.size() == 0) { throw new IllegalArgumentException(String .format("Illegal relative path '%s' within context '%s'", path, context.getFullName())); } name.pop(); continue; } if (p[i].equals(".")) { continue; } name.push(p[i]); } return StringUtils.join(name, '/'); }
From source file:cf.adriantodt.utils.HTML2Discord.java
public static String toPlainText(String discordFormatMessage) { String strippedContent;/*from www . j av a2s. c om*/ //all the formatting keys to keep track of String[] keys = new String[] { "*", "_", "`", "~~" }; //find all tokens (formatting strings described above) TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start)); for (String key : keys) { Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(discordFormatMessage); while (matcher.find()) { tokens.add(new FormatToken(key, matcher.start())); } } //iterate over all tokens, find all matching pairs, and add them to the list toRemove Stack<FormatToken> stack = new Stack<>(); List<FormatToken> toRemove = new ArrayList<>(); boolean inBlock = false; for (FormatToken token : tokens) { if (stack.empty() || !stack.peek().format.equals(token.format) || stack.peek().start + token.format.length() == token.start) { //we are at opening tag if (!inBlock) { //we are outside of block -> handle normally if (token.format.equals("`")) { //block start... invalidate all previous tags stack.clear(); inBlock = true; } stack.push(token); } else if (token.format.equals("`")) { //we are inside of a block -> handle only block tag stack.push(token); } } else if (!stack.empty()) { //we found a matching close-tag toRemove.add(stack.pop()); toRemove.add(token); if (token.format.equals("`") && stack.empty()) { //close tag closed the block inBlock = false; } } } //sort tags to remove by their start-index and iteratively build the remaining string Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start)); StringBuilder out = new StringBuilder(); int currIndex = 0; for (FormatToken formatToken : toRemove) { if (currIndex < formatToken.start) { out.append(discordFormatMessage.substring(currIndex, formatToken.start)); } currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < discordFormatMessage.length()) { out.append(discordFormatMessage.substring(currIndex)); } //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~"); return strippedContent; }