Java Code Examples for java.util.Stack.push()

The following are Jave code examples for showing how to use push() of the java.util.Stack class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tap17-muggl-javaee   File: CompareFloat.java   View Source Code Vote up 6 votes
/**
 * Execute the inheriting instruction.
 *
 * @param frame The currently executed frame.
 */
@Override
public void execute(Frame frame) {
	Stack<Object> stack = frame.getOperandStack();
	Float value2 = (Float) stack.pop();
	Float value1 = (Float) stack.pop();
	if (value1.isNaN() || value2.isNaN()) {
		stack.push(getPushValueForNaN());
	} else if (value1 > value2) {
		stack.push(Integer.valueOf(1));
	} else if (value1 < value2) {
		stack.push(Integer.valueOf(-1));
	} else {
		stack.push(Integer.valueOf(0));
	}
}
 
Example 2
Project: LinkedList_learning   File: LinkedList.java   View Source Code Vote up 6 votes
public static Boolean isPalindrome2(Node head) {
	if (head == null)
		return false;
	Node slow = head;
	Node fast = head;
	Stack<Integer> sta = new Stack<Integer>();
	while (fast != null && fast.next != null) {
		sta.push(slow.value);
		slow = slow.next;
		fast = fast.next.next;
	}
	if (fast != null)// 如果有奇数个节点,slow再往后移动一个
		slow = slow.next;

	while (!sta.isEmpty()) {
		if (sta.pop() != slow.value)
			return false;
		slow = slow.next;
	}
	return true;
}
 
Example 3
Project: incubator-netbeans   File: BeansTestCase.java   View Source Code Vote up 6 votes
public static TreePath getTreePath(JTreeOperator treeOperator, String targetNode, NodeConverter converter) {
    Stack<TreeNode> lifo = new Stack<TreeNode>();        
    lifo.push((TreeNode) treeOperator.getRoot());
    while(!lifo.isEmpty()) {
        TreeNode actNode = lifo.pop();
        if(targetNode.equals(converter.getDisplayName(actNode))) {
            List<TreeNode> path = new LinkedList<TreeNode>();
            path.add(actNode);
            actNode = actNode.getParent();
            while(actNode!=null) {
                path.add(0,actNode);
                actNode = actNode.getParent();
            }
            TreeNode[] res = path.toArray(new TreeNode[path.size()]);                
            return new TreePath(res);
        }
        final Enumeration children = actNode.children();            
        while(children.hasMoreElements()) {
            lifo.add((TreeNode)children.nextElement());
        }            
    }
    return null;
}
 
Example 4
Project: openjdk-jdk10   File: QuotedStringTokenizer.java   View Source Code Vote up 6 votes
private boolean unmatchedQuotesIn(final String str) {
    final Stack<Character> quoteStack = new Stack<>();
    for (int i = 0; i < str.length(); i++) {
        final char c = str.charAt(i);
        for (final char q : this.quotes) {
            if (c == q) {
                if (quoteStack.isEmpty()) {
                    quoteStack.push(c);
                } else {
                    final char top = quoteStack.pop();
                    if (top != c) {
                        quoteStack.push(top);
                        quoteStack.push(c);
                    }
                }
            }
        }
    }

    return !quoteStack.isEmpty();
}
 
Example 5
Project: spellchecker_ta   File: Sandhi.java   View Source Code Vote up 6 votes
static boolean type5(Stack s)
{
	//5 - doubling
	byte[] topElmt = ((Entry)s.peek()).getPart();
	byte[] oldTopElmt = topElmt;
	byte[] sandhi = BooleanMethod.endswith_doubling_Letter(topElmt);
	if(sandhi != null)
	{
		//System.out.println(x + "type 5");
		s.pop();
		topElmt = ByteMeth.subArray(topElmt,0,
			topElmt.length-sandhi.length);
		s.push(new Entry(sandhi,Tag.Sandhi));
		s.push(new Entry(topElmt,-1,oldTopElmt));
		return true;
	}
	return false;
}
 
Example 6
Project: tap17-muggl-javaee   File: F2l.java   View Source Code Vote up 5 votes
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 * @throws ExecutionException Thrown in case of fatal problems during the execution.
 */
@Override
@SuppressWarnings("unused")
public void execute(Frame frame) throws ExecutionException {
	Stack<Object> stack = frame.getOperandStack();
	stack.push(((Float) stack.pop()).longValue());
}
 
Example 7
Project: incubator-netbeans   File: XMLBraceMatcher.java   View Source Code Vote up 5 votes
/**
 * Checks to see if an end tag exists for a start tag at a given offset.
 * @param document
 * @param offset
 * @return true if an end tag is found for the start, false otherwise.
 */
public static boolean hasEndTag(Document document, int offset, String startTag) {
    AbstractDocument doc = (AbstractDocument)document;
    doc.readLock();
    try {
        TokenHierarchy th = TokenHierarchy.get(doc);
        TokenSequence ts = th.tokenSequence();
        Token token = findTokenAtContext(ts, offset);
        Stack<String> stack = new Stack<String>();
        while(ts.moveNext()) {
            Token t = ts.token();
            if(XMLTokenId.TAG != t.id())
                continue;
            String tag = t.text().toString();
            if(">".equals(tag))
                continue;
            if(stack.empty()) {
                if(("</"+startTag).equals(tag)) {
                    stack.empty();
                    stack = null;
                    return true;
                }
            } else {                
                if(tag.equals("/>") || ("</"+stack.peek()).equals(tag)) {
                    stack.pop();
                    continue;
                }
            }
            stack.push(tag.substring(1));
        }            
    } finally {
        doc.readUnlock();
    }
    
    return false;
}
 
Example 8
Project: tap17-muggl-javaee   File: Dup_x2.java   View Source Code Vote up 5 votes
/**
 * Execute the instruction symbolically.
 * @param frame The currently executed frame.
 * @throws SymbolicExecutionException Thrown in case of fatal problems during the symbolic execution.
 */
@Override
public void executeSymbolically(Frame frame) throws SymbolicExecutionException {
	try {
		Stack<Object> stack = frame.getOperandStack();
		Object value1 = stack.pop();
		Object value2 = stack.pop();
		if (!checkCategory2(value1) && checkCategory2(value2)) {
			// Form 2: value1 is a type of category 1, while value2 is a type of category 2.
			stack.push(value2);
			stack.push(value1);
		} else {
			Object value3 = stack.pop();
			if (!(checkCategory2(value1) || checkCategory2(value2) || checkCategory2(value3))) {
				// Form 1: All three values are types of category 1.
				stack.push(value1);
				stack.push(value3);
				stack.push(value2);
				stack.push(value1);
			} else {
				// Recovery.
				stack.push(value3);
				stack.push(value2);
				stack.push(value1);
				throw new ExecutionException("When using " + getName() + " either the three topmost values of the operand stack must not be category 2 types, or the topmost value must be a category 1 type, while the second one must be a category 2 type.");
			}
		}
	} catch (ExecutionException e) {
		symbolicExecutionFailedWithAnExecutionException(e);
	}
}
 
Example 9
Project: tap17-muggl-javaee   File: DNeg.java   View Source Code Vote up 5 votes
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 * @throws ExecutionException Thrown in case of fatal problems during the execution.
 */
@Override
@SuppressWarnings("unused")
public void execute(Frame frame) throws ExecutionException {
	Stack<Object> stack = frame.getOperandStack();
	stack.push((Double) stack.pop() * -1D);
}
 
Example 10
Project: APCSAB   File: BXT.java   View Source Code Vote up 5 votes
public void preorderTraverse() {
    Stack<TreeNode<String>> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode<String> node = stack.pop();
        if (null == node) continue;
        System.out.print(node.getValue() + " ");
        stack.push(node.getRight());
        stack.push(node.getLeft());
    }
}
 
Example 11
Project: avro-compatibility   File: SchemaCompatibility.java   View Source Code Vote up 5 votes
private SchemaCompatibilityResult checkReaderEnumContainsAllWriterEnumSymbols(
    final Schema reader, final Schema writer, final Stack<String> location) {
  SchemaCompatibilityResult result = SchemaCompatibilityResult.compatible();
  location.push("symbols");
  final Set<String> symbols = new TreeSet<String>(writer.getEnumSymbols());
  symbols.removeAll(reader.getEnumSymbols());
  if (!symbols.isEmpty()) {
    result = SchemaCompatibilityResult.incompatible(
        SchemaIncompatibilityType.MISSING_ENUM_SYMBOLS, reader, writer,
        symbols.toString(), location);
  }
  // POP "symbols" literal
  location.pop();
  return result;
}
 
Example 12
Project: lyra2-java   File: CommandLine.java   View Source Code Vote up 5 votes
private int applyValueToSingleValuedField(Field field,
                                          Range arity,
                                          Stack<String> args,
                                          Class<?> cls,
                                          Set<Field> initialized) throws Exception {
    boolean noMoreValues = args.isEmpty();
    String value = args.isEmpty() ? null : trim(args.pop()); // unquote the value
    int result = arity.min; // the number or args we need to consume

    // special logic for booleans: BooleanConverter accepts only "true" or "false".
    if ((cls == Boolean.class || cls == Boolean.TYPE) && arity.min <= 0) {

        // boolean option with arity = 0..1 or 0..*: value MAY be a param
        if (arity.max > 0 && ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value))) {
            result = 1;            // if it is a varargs we only consume 1 argument if it is a boolean value
        } else {
            if (value != null) {
                args.push(value); // we don't consume the value
            }
            Boolean currentValue = (Boolean) field.get(command);
            value = String.valueOf(currentValue == null ? true : !currentValue); // #147 toggle existing boolean value
        }
    }
    if (noMoreValues && value == null) {
        return 0;
    }
    if (initialized != null) {
        if (initialized.contains(field) && !isOverwrittenOptionsAllowed()) {
            throw new OverwrittenOptionException(optionDescription("", field, 0) +  " should be specified only once");
        }
        initialized.add(field);
    }
    ITypeConverter<?> converter = getTypeConverter(cls);
    Object objValue = tryConvert(field, -1, converter, value, cls);
    field.set(command, objValue);
    return result;
}
 
Example 13
Project: tap17-muggl-javaee   File: LAdd.java   View Source Code Vote up 5 votes
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 * @throws ExecutionException Thrown in case of fatal problems during the execution.
 */
@Override
@SuppressWarnings("unused")
public void execute(Frame frame) throws ExecutionException {
	Stack<Object> stack = frame.getOperandStack();
	Long value2 = (Long) stack.pop();
	Long value1 = (Long) stack.pop();
	stack.push(value1 + value2);
}
 
Example 14
Project: tap17-muggl-javaee   File: LOr.java   View Source Code Vote up 4 votes
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 */
@Override
public void execute(Frame frame) {
	Stack<Object> stack = frame.getOperandStack();
	stack.push((Long) stack.pop() | (Long) stack.pop());
}
 
Example 15
Project: alfresco-repository   File: BaseBehaviour.java   View Source Code Vote up 4 votes
/**
 * Disable this behaviour for the curent thread
 */
public void disable() 
{
    Stack<Integer> stack = disabled.get();
    stack.push(hashCode());
}
 
Example 16
Project: athena   File: JsonRpcReaderUtil.java   View Source Code Vote up 4 votes
/**
 * Decode the bytes to Json object.
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 * @throws IOException IOException
 * @throws JsonParseException JsonParseException
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext)
        throws JsonParseException, IOException {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}
 
Example 17
Project: alfresco-repository   File: RepositoryNodeRefResolver.java   View Source Code Vote up 4 votes
@Override
public NodeRef createQNamePath(String[] reference, String[] names)
{
    Stack<String> notFoundStack = new Stack<>();
    Stack<String> notFoundNameStack = new Stack<>();
    NodeRef found;
    if (reference == null || reference.length == 0)
    {
        found = getRootHome();
    }
    else
    {
        NodeRef parentNodeRef = null;
        for (int i = reference.length; i > 0; i--)
        {
            String[] parent = new String[i];
            System.arraycopy(reference,
                             0,
                             parent,
                             0,
                             i);
            parentNodeRef = resolveQNameReference(parent);
            if (parentNodeRef != null)
            {
                break;
            }
            else
            {
                if (names != null)
                {
                    int offset = reference.length - i;
                    if (offset < names.length)
                    {
                        notFoundNameStack.push(names[names.length - 1 - offset]);
                    }
                }
                notFoundStack.push(reference[i - 1]);
            }
        }
        while (!notFoundStack.isEmpty())
        {
            String stringQNameToCreate = notFoundStack.pop();
            QName qNameToCreate = QName.createQName(stringQNameToCreate,
                                                    namespacePrefixResolver);
            String nameToCreate;
            if (!notFoundNameStack.isEmpty())
            {
                nameToCreate = notFoundNameStack.pop();
            }
            else
            {
                nameToCreate = qNameToCreate.getLocalName();
            }
            final HashMap<QName, Serializable> newProperties = new HashMap<QName, Serializable>();
            newProperties.put(ContentModel.PROP_NAME,
                              nameToCreate);
            ChildAssociationRef newAssoc = nodeService.createNode(parentNodeRef,
                                                                  ContentModel.ASSOC_CONTAINS,
                                                                  qNameToCreate,
                                                                  ContentModel.TYPE_FOLDER,
                                                                  newProperties);
            parentNodeRef = newAssoc.getChildRef();
        }

        found = parentNodeRef;
    }

    return found;

}
 
Example 18
Project: VillagerTrades   File: JsonToNBT.java   View Source Code Vote up 4 votes
static int topTagsCount(String str) throws NBTException
{
	int i = 0;
	boolean flag = false;
	Stack<Character> stack = new Stack();

	for (int j = 0; j < str.length(); ++j)
	{
		char c0 = str.charAt(j);

		if (c0 == 34)
		{
			if (isCharEscaped(str, j))
			{
				if (!flag)
				{
					throw new NBTException("Illegal use of \\\": " + str);
				}
			}
			else
			{
				flag = !flag;
			}
		}
		else if (!flag)
		{
			if (c0 != 123 && c0 != 91)
			{
				if (c0 == 125 && (stack.isEmpty() || stack.pop().charValue() != 123))
				{
					throw new NBTException("Unbalanced curly brackets {}: " + str);
				}

				if (c0 == 93 && (stack.isEmpty() || stack.pop().charValue() != 91))
				{
					throw new NBTException("Unbalanced square brackets []: " + str);
				}
			}
			else
			{
				if (stack.isEmpty())
				{
					++i;
				}

				stack.push(Character.valueOf(c0));
			}
		}
	}

	if (flag)
	{
		throw new NBTException("Unbalanced quotation: " + str);
	}
	else if (!stack.isEmpty())
	{
		throw new NBTException("Unbalanced brackets: " + str);
	}
	else
	{
		if (i == 0 && !str.isEmpty())
		{
			i = 1;
		}

		return i;
	}
}
 
Example 19
Project: tap17-muggl-javaee   File: CGUtilities.java   View Source Code Vote up 4 votes
/**
 * Control graphs found by the {@link CGGenerator} are not reduced to edges between
 * basic blocks. In fact, they contain any edge between nodes whereas nodes are all instructions
 * of a method. If a control graph is desired that only contains edges between basic blocks and
 * thus treats every basic block as an edge, this method can be used to determine the basic
 * blocks.
 * 
 * The start of the basic block is the last instruction in a sequence of instructions that can
 * be reached by jumps. The following blocks never are jump targets and will always be processed
 * in sequence. The last instruction in the block is either an conditional jump (at this place
 * including switching instructions and instructions that may throw exceptions) or the
 * instruction prior to a jump target. Basic blocks must not contain a sequence of instructions.
 * In fact, they can be made up from one instruction only.
 * 
 * @param controlGraph The control graph to extract basic blocks from.
 * @return The basic blocks as a Map of integers to integers where the first one is pc the block
 *         starts at and the second one is the pc the block ends at.
 */
public static Map<Integer, Integer> getBasicBlocks(ControlGraph controlGraph) {
	// Preparation.
	Map<Integer, Integer> basicBlocks = new HashMap<Integer, Integer>();
	Map<Integer, Set<Integer>> cgCoverageMap = controlGraph.getControlGraph();
	
	Instruction[] instructions;
	try {
		instructions = controlGraph.getMethod().getInstructionsAndOtherBytes();
	} catch (InvalidInstructionInitialisationException e) {
		// This cannot happen. At this point, the Method has been read already.
		return null;
	}
	
	/*
	 * Get the basic blocks. For performance reasons, the strategy is rather simple: Process the
	 * graph by following its edges. Records basic blocks while doing so. Whenever a instruction
	 * with more than one edge is encountered, branch and save the basic block. Even though the
	 * control-flow is not interrupted, unconditional jumps will also end a basic block. On any
	 * jump that has a target with a lower pc than the current pc is, check whether the target
	 * already is the beginning instruction of a basic block. If it is, discard hat branch. If
	 * it is not, proceed, but check whether a basic block has been split into two by doing so.
	 */
	Stack<Integer> stack = new Stack<Integer>();
	stack.push(0);
	while (!stack.isEmpty()) {
		Integer startedAt = stack.pop();
		Integer pcCur = startedAt;
		Set<Integer> edges;
		// Continue until an instruction with multiple edges was found.
		for (edges = cgCoverageMap.get(pcCur); edges.size() == 1 && !(instructions[pcCur] instanceof JumpAlways);) {
			pcCur = edges.iterator().next();
		}
		
		// Save the basic block.
		basicBlocks.put(startedAt, pcCur);
		
		// Branch.
		for (Integer target : edges) {
			// Only continue when the jump target is not the start of a basic block already.
			if (basicBlocks.containsKey(target)) {
				// Check whether it is a jump into a basic block.
				Integer basicBlockStart = inBasicBlock(target, basicBlocks);
				if (basicBlockStart != null) {
					// Split the block.
					Integer basicBlockEnd = basicBlocks.get(basicBlockStart);
					basicBlocks.remove(basicBlockStart);
					Integer precedeTarget;
					int a = target - 1;
					while (instructions[a] == null) { a--; }
					precedeTarget = a;
					basicBlocks.put(basicBlockStart, precedeTarget);
					basicBlocks.put(target, basicBlockEnd);
				} else {
					// Process that branch.
					stack.push(target);
				}
			}
		}
	}
	
	// Finished.
	return basicBlocks;
}
 
Example 20
Project: powertext   File: RSyntaxTextAreaEditorKit.java   View Source Code Vote up 4 votes
/**
 * Discovers the name of the tag being closed.  Assumes standard
 * SGML-style markup tags.
 *
 * @param doc The document to parse.
 * @param dot The location of the caret.  This should be right after
 *        the start of a closing tag token (e.g. "<code>&lt;/</code>"
 *        or "<code>[</code>" in the case of BBCode).
 * @return The name of the tag to close, or <code>null</code> if it
 *         could not be determined.
 */
private String discoverTagName(RSyntaxDocument doc, int dot) {

	Stack<String> stack = new Stack<String>();

	Element root = doc.getDefaultRootElement();
	int curLine = root.getElementIndex(dot);

	for (int i=0; i<=curLine; i++) {

		Token t = doc.getTokenListForLine(i);
		while (t!=null && t.isPaintable()) {

			if (t.getType()==Token.MARKUP_TAG_DELIMITER) {
				if (t.isSingleChar('<') || t.isSingleChar('[')) {
					t = t.getNextToken();
					while (t!=null && t.isPaintable()) {
						if (t.getType()==Token.MARKUP_TAG_NAME ||
								// Being lenient here and also checking
								// for attributes, in case they
								// (incorrectly) have whitespace between
								// the '<' char and the element name.
								t.getType()==Token.MARKUP_TAG_ATTRIBUTE) {
							stack.push(t.getLexeme());
							break;
						}
						t = t.getNextToken();
					}
				}
				else if (t.length()==2 && t.charAt(0)=='/' &&
						(t.charAt(1)=='>' ||
								t.charAt(1)==']')) {
					if (!stack.isEmpty()) { // Always true for valid XML
						stack.pop();
					}
				}
				else if (t.length()==2 &&
						(t.charAt(0)=='<' || t.charAt(0)=='[') &&
						t.charAt(1)=='/') {
					String tagName = null;
					if (!stack.isEmpty()) { // Always true for valid XML
						tagName = stack.pop();
					}
					if (t.getEndOffset()>=dot) {
						return tagName;
					}
				}
			}

			t = t==null ? null : t.getNextToken();

		}

	}

	return null; // Should never happen

}