Example usage for java.util Stack pop

List of usage examples for java.util Stack pop

Introduction

In this page you can find the example usage for java.util Stack pop.

Prototype

public synchronized E pop() 

Source Link

Document

Removes the object at the top of this stack and returns that object as the value of this function.

Usage

From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java

public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost,
        float substitutionCost, float omissionCost, Distance distance) {
    // build first row
    List<Float> row = range(transWord.length() + 1);

    // results/*from   ww  w .  j av  a  2  s .com*/
    Set<SuggestionResult> results = new HashSet<SuggestionResult>();

    // iteratively (to prevent stack overflow) search each branch of the graph
    // a stack of paths to traverse. This prevents the StackOverflowException.
    Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>();
    for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) {
        long child = iter.next();
        char c = getChar(child);

        StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(),
                String.valueOf(c), row);
        stack.push(entry);
    }

    // thread to control time to search for suggestions
    mAreTimeAvailable = true;
    mTimerTask = new TimerTask() {

        @Override
        public void run() {
            //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!");
            mAreTimeAvailable = false;
        }
    };
    mTimer = new Timer();
    mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions

    while (!stack.empty() && mAreTimeAvailable) {
        StackLevenshteinEntry entry = stack.pop();
        List<Float> previousRow = entry.previousRow;

        int columns = entry.chars.length + 1;
        List<Float> currentRow = new LinkedList<Float>();
        currentRow.add(previousRow.get(0) + omissionCost);

        // build one row for the letter, with a column for each letter in the target word, 
        // plus one for the empty string at column 0
        for (int column = 1; column < columns; column++) {
            // cost * braille_distance
            float insertCost = currentRow.get(column - 1) + insertionCost;// * 
            //getInsertionDistance(entry.chars, column-1, getChar(entry.node));
            float omitCost = previousRow.get(column) + omissionCost;
            float substituteCost = previousRow.get(column - 1);

            if (entry.chars[column - 1] != getChar(entry.node))
                substituteCost += substitutionCost
                        * distance.getDistance(entry.chars[column - 1], getChar(entry.node));

            currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost)));
        }

        // if last entry in the row indicates the optimal cost is less than the maximum cost,
        // and there is a word in this node, then add it.
        int last = currentRow.size() - 1;
        if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) {
            results.add(new SuggestionResult(entry.subword, currentRow.get(last)));
        }

        // if any entries in the row are less than the maximum cost, then iteratively search each branch
        if (min(currentRow) <= maxCost) {
            for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) {
                // get child
                long child = iter.next();

                // build subword
                StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars,
                        entry.subword + getChar(child), currentRow);

                // search that branch
                stack.push(nextEntry);
            }
        }
    }

    mTimer.cancel();

    // return list of results
    return results;
}

From source file:org.alfresco.repo.transfer.AlienProcessorImpl.java

/**
 * Top down un-invasion/*from w  ww.  ja v  a 2s.  com*/
 * <p>
 * Steps down the tree retreating from all the invaded nodes.
 * <p>
 * The retreat will stop is there is a "sub-invasion".
 * <p>   
 * @param nodeRef the top of the tree
 * @param fromRepositoryId the repository that is retreating.
 */
private void retreatDownwards(NodeRef nodeRef, String fromRepositoryId) {
    Stack<NodeRef> nodesToRetreat = new Stack<NodeRef>();
    nodesToRetreat.add(nodeRef);

    /**
     * Now go and do the retreat.        
     */
    while (!nodesToRetreat.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("retreat :" + nodeRef + ", repoId:" + fromRepositoryId);
        }

        /**
         *  for the current node and all alien children
         *  
         *  if they are "from" the retreating repository then 
         */
        NodeRef currentNodeRef = nodesToRetreat.pop();

        log.debug("retreatNode:" + currentNodeRef);

        if (getNodeService().hasAspect(currentNodeRef, TransferModel.ASPECT_ALIEN)) {
            // Yes this is an alien node
            List<String> invadedBy = (List<String>) getNodeService().getProperty(currentNodeRef,
                    TransferModel.PROP_INVADED_BY);

            String parentRepoId;
            if (nodeService.hasAspect(currentNodeRef, TransferModel.ASPECT_TRANSFERRED)) {
                log.debug("node is transferred");
                parentRepoId = (String) nodeService.getProperty(currentNodeRef,
                        TransferModel.PROP_FROM_REPOSITORY_ID);
            } else {
                log.debug("node is local");
                parentRepoId = descriptorService.getCurrentRepositoryDescriptor().getId();
            }

            if (fromRepositoryId.equalsIgnoreCase(parentRepoId)) {
                // This node is "owned" by the retreating repo
                // Yes we are invaded by fromRepositoryId
                if (invadedBy.size() == 1) {
                    // we are invaded by a single repository which must be fromRepositoryId
                    log.debug("no longe alien:" + currentNodeRef);
                    getNodeService().removeAspect(currentNodeRef, TransferModel.ASPECT_ALIEN);
                } else {
                    invadedBy.remove(parentRepoId);
                    getNodeService().setProperty(currentNodeRef, TransferModel.PROP_INVADED_BY,
                            (Serializable) invadedBy);
                }

                //List<ChildAssociationRef> refs = getNodeService().getChildAssocs(currentNodeRef);
                List<ChildAssociationRef> refs = nodeService.getChildAssocsByPropertyValue(currentNodeRef,
                        TransferModel.PROP_INVADED_BY, fromRepositoryId);
                for (ChildAssociationRef ref : refs) {
                    if (log.isDebugEnabled()) {
                        log.debug("will need to check child:" + ref);
                    }
                    nodesToRetreat.push(ref.getChildRef());
                }
            }
        }
    }
}

From source file:com.autentia.bcbp.elements.ConditionalItemsUnique.java

public ConditionalItemsUnique(String passengerDescription, String sourceCheckin,
        String sourceBoardingPassIssuance, String dateOfIssueOfBoardingPass, String documentType,
        String airlineDesignatorOfBoardingPassIssuer, String baggageTagLicencePlateNumber,
        String firstNCBaggageTagLicencePlateNumber, String secondNCBaggageTagLicencePlateNumber) {
    super();//from  ww  w . j a va  2  s. c o m

    Stack<Item> items = new Stack<Item>();

    items.push(new Item(passengerDescription, passengerDescriptionLength, 142, PaddingType.String));
    items.push(new Item(sourceCheckin, sourceCheckinLength, 143, PaddingType.String));
    items.push(new Item(sourceBoardingPassIssuance, sourceBoardingPassIssuanceLength, 18, PaddingType.String));
    items.push(new Item(dateOfIssueOfBoardingPass, dateOfIssueOfBoardingPassLength, 108, PaddingType.Number));
    items.push(new Item(documentType, documentTypeLength, 19, PaddingType.String));
    items.push(new Item(airlineDesignatorOfBoardingPassIssuer, airlineDesignatorOfBoardingPassIssuerLength, 20,
            PaddingType.String));
    items.push(new Item(baggageTagLicencePlateNumber, baggageTagLicencePlateNumberLength, 236,
            PaddingType.String));
    items.push(new Item(firstNCBaggageTagLicencePlateNumber, firstNCBaggageTagLicencePlateNumberLength, 89,
            PaddingType.String));
    items.push(new Item(secondNCBaggageTagLicencePlateNumber, secondNCBaggageTagLicencePlateNumberLength, 118,
            PaddingType.String));

    final StringBuilder codeBuilder = new StringBuilder();
    boolean starting = true;
    while (!items.isEmpty()) {
        Item item = items.pop();
        if (starting && StringUtils.isNotBlank(item.getEncoded()) || !removeEndingEmptyElements)
            starting = false;
        if (!starting)
            codeBuilder.insert(0, item.getEncoded());
    }

    final String baseCode = codeBuilder.toString();

    if (StringUtils.isBlank(baseCode))
        code = "";
    else
        code = ">"
                + BCBPversion + StringUtils
                        .leftPad(Integer.toHexString(baseCode.length()), variableSizeLength, "0").toUpperCase()
                + baseCode;
}

From source file:com.udojava.evalex.Expression.java

/**
 * Evaluates the expression./*from w  ww.  j  a  v  a 2 s. com*/
 *
 * @return The result of the expression.
 */
public MyComplex eval() {
    Stack<LazyNumber> stack = new Stack<>();

    for (final String token : getRPN()) {
        if (operators.containsKey(token)) {
            final LazyNumber v1 = stack.pop();
            final LazyNumber v2 = stack.pop();
            LazyNumber number = () -> operators.get(token).eval(v2.eval(), v1.eval());
            stack.push(number);
        } else if (mainVars.getMap().containsKey(token)) {
            MyComplex v = mainVars.get(token);
            if (v.type == ValueType.ARRAY) {
                stack.push(() -> v);
            } else {
                PitDecimal bd = new PitDecimal(v.real, v.imaginary);
                bd.type = v.type;
                bd.setVarToken(token);
                stack.push(() -> bd);
            }
        } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) {
            LazyFunction f = functions.get(token.toUpperCase(Locale.ROOT));
            ArrayList<LazyNumber> p = new ArrayList<>(!f.numParamsVaries() ? f.getNumParams() : 0);
            // pop parameters off the stack until we hit the start of
            // this function's parameter list
            while (!stack.isEmpty() && stack.peek() != PARAMS_START) {
                p.add(0, stack.pop());
            }
            if (stack.peek() == PARAMS_START) {
                stack.pop();
            }
            LazyNumber fResult = f.lazyEval(p);
            stack.push(fResult);
        } else if ("(".equals(token)) {
            stack.push(PARAMS_START);
        } else {
            MyComplex bd;
            if (token.endsWith("i")) {
                String str = token.substring(0, token.length() - 1);
                if (str.isEmpty())
                    str = "1";
                bd = new MyComplex("0", str);
            } else {
                bd = new MyComplex(token);
            }
            MyComplex finalBd = bd;
            stack.push(() -> finalBd); // blank constant
        }
    }
    return stack.pop().eval();
}

From source file:com.webcohesion.ofx4j.io.TestBaseOFXReader.java

/**
 * tests using sax to parse an OFX doc./* ww w .  j av a 2s. c  o  m*/
 */
public void testVersion2() throws Exception {
    BaseOFXReader reader = new BaseOFXReader() {
        protected void parseV1FromFirstElement(Reader reader) throws IOException, OFXParseException {
            fail();
        }
    };
    final Map<String, String> headers = new HashMap<String, String>();
    final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>();
    TreeMap<String, Object> root = new TreeMap<String, Object>();
    aggregateStack.push(root);

    reader.setContentHandler(new DefaultHandler() {

        @Override
        public void onHeader(String name, String value) {
            LOG.debug(name + ":" + value);
            headers.put(name, value);
        }

        @Override
        public void onElement(String name, String value) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + name + "=" + value);

            aggregateStack.peek().put(name, value);
        }

        @Override
        public void startAggregate(String aggregateName) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + aggregateName + " {");

            TreeMap<String, Object> aggregate = new TreeMap<String, Object>();
            aggregateStack.peek().put(aggregateName, aggregate);
            aggregateStack.push(aggregate);
        }

        @Override
        public void endAggregate(String aggregateName) {
            aggregateStack.pop();

            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + "}");
        }
    });
    reader.parse(BaseOFXReader.class.getResourceAsStream("example-response.ofx2"));
    assertEquals(5, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());
}

From source file:org.alfresco.web.app.AlfrescoNavigationHandler.java

/**
 * Closes the current dialog or wizard/*  w  w  w  . j a  v a2  s.  co m*/
 * 
 * @param context FacesContext
 * @param fromAction The fromAction
 * @param outcome The outcome
 * @param dialog true if a dialog is being closed, false if a wizard is being closed
 */
protected void handleDialogOrWizardClose(FacesContext context, String fromAction, String outcome,
        boolean dialog) {
    String closingItem = dialog ? "dialog" : "wizard";

    // if we are closing a wizard or dialog take the view off the 
    // top of the stack then decide whether to use the view
    // or any overridden outcome that may be present
    if (getViewStack(context).empty() == false) {
        // is there an overidden outcome?
        String overriddenOutcome = getOutcomeOverride(outcome);
        if (overriddenOutcome == null) {
            // there isn't an overidden outcome so go back to the previous view
            if (logger.isDebugEnabled())
                logger.debug("Closing " + closingItem);

            // determine how many levels of dialog we need to close
            int numberToClose = getNumberToClose(outcome);

            Object stackObject = null;
            if (numberToClose == 1) {
                // just closing one dialog so get the item from the top of the stack
                stackObject = getViewStack(context).pop();

                if (logger.isDebugEnabled())
                    logger.debug("Popped item from the top of the view stack: " + stackObject);
            } else {
                // check there are enough items on the stack, if there
                // isn't just get the last one (effectively going back
                // to the beginning)
                Stack viewStack = getViewStack(context);
                int itemsOnStack = viewStack.size();
                if (itemsOnStack < numberToClose) {
                    if (logger.isDebugEnabled())
                        logger.debug("Returning to first item on the view stack as there aren't "
                                + numberToClose + " containers to close!");

                    numberToClose = itemsOnStack;
                }

                // pop the right object from the stack
                for (int x = 1; x <= numberToClose; x++) {
                    stackObject = viewStack.pop();
                }

                if (logger.isDebugEnabled())
                    logger.debug("Popped item from the stack: " + stackObject);
            }

            // get the appropriate view id for the stack object
            String newViewId = getViewIdFromStackObject(context, stackObject);

            // go to the appropraite page
            goToView(context, newViewId);
        } else {
            // we also need to empty the dialog stack if we have been given
            // an overidden outcome as we could be going anywhere in the app.
            // grab the current top item first though in case we need to open
            // another dialog or wizard
            if (OUTCOME_BROWSE.equals(overriddenOutcome) == false) {
                String previousViewId = getViewIdFromStackObject(context, getViewStack(context).peek());
                getViewStack(context).clear();

                if (logger.isDebugEnabled())
                    logger.debug("Closing " + closingItem + " with an overridden outcome of '"
                            + overriddenOutcome + "'");

                // if the override is calling another dialog or wizard come back through
                // the navigation handler from the beginning
                if (isDialog(overriddenOutcome) || isWizard(overriddenOutcome)) {
                    // set the view id to the page at the top of the stack so when
                    // the new dialog or wizard closes it goes back to the correct page
                    context.getViewRoot().setViewId(previousViewId);

                    if (logger.isDebugEnabled()) {
                        logger.debug("view stack: " + getViewStack(context));
                        logger.debug("Opening '" + overriddenOutcome + "' after " + closingItem
                                + " close using view id: " + previousViewId);
                    }

                    this.handleNavigation(context, fromAction, overriddenOutcome);
                } else {
                    navigate(context, fromAction, overriddenOutcome);
                }
            } else {
                handleBrowseDispatch(context, fromAction, overriddenOutcome);

                // ALF-6661, always clear the view stack with an overridden outcome
                getViewStack(context).clear();
            }
        }
    } else {
        // we are trying to close a dialog when one hasn't been opened!
        // return to the main page of the app (print warning if debug is enabled)
        if (logger.isDebugEnabled()) {
            logger.debug("Attempting to close a " + closingItem
                    + " with an empty view stack, returning 'browse' outcome");
        }

        navigate(context, fromAction, OUTCOME_BROWSE);
    }
}

From source file:net.dv8tion.jda.entities.impl.MessageImpl.java

@Override
public String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //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(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from  ww w .  j ava  2s.  c om
        }

        //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(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.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;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.java

/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 *///from   w w  w  . ja v  a2  s .c om
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final WebClient client = getWindow().getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    } else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE and FF seem both to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = getWindow();
        final ContextFactory cf = client.getJavaScriptEngine().getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack = (Stack<Scriptable>) cx
                        .getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                } finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().createJavascriptXMLHttpRequestJob(cf,
                action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = getWindow().getWebWindow().getJobManager().addJob(job, page);
    }
}

From source file:com.amalto.core.storage.StorageMetadataUtils.java

private static void __paths(ComplexTypeMetadata type, FieldMetadata target, Stack<FieldMetadata> currentPath,
        Set<List<FieldMetadata>> foundPaths, Set<TypeMetadata> processedTypes) {
    if (Storage.PROJECTION_TYPE.equals(type.getName()) && type.hasField(target.getName())) {
        currentPath.push(type.getField(target.getName()));
    }/*w w  w  .ja  va2  s  .c  om*/
    //
    Collection<FieldMetadata> fields = type.getFields();
    for (FieldMetadata current : fields) {
        currentPath.push(current);
        if (current.equals(target)) {
            foundPaths.add(new ArrayList<FieldMetadata>(currentPath));
        }
        if (current instanceof ContainedTypeFieldMetadata) {
            ComplexTypeMetadata containedType = ((ContainedTypeFieldMetadata) current).getContainedType();
            _paths(containedType, target, currentPath, foundPaths, processedTypes);
            for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                for (FieldMetadata field : subType.getFields()) {
                    if (field.getDeclaringType().equals(subType)) {
                        _paths(subType, target, currentPath, foundPaths, processedTypes);
                    }
                }
            }
        } else if (current instanceof ReferenceFieldMetadata) {
            ComplexTypeMetadata referencedType = ((ReferenceFieldMetadata) current).getReferencedType();
            if (!referencedType.isInstantiable()) {
                if (processedTypes.contains(referencedType)) {
                    Collection<FieldMetadata> tempFields = referencedType.getFields();
                    for (FieldMetadata tempCurrent : tempFields) {
                        if (tempCurrent.equals(target)) {
                            currentPath.push(tempCurrent);
                            foundPaths.add(new ArrayList<FieldMetadata>(currentPath));
                            currentPath.pop();
                        }
                    }
                }
                _paths(referencedType, target, currentPath, foundPaths, processedTypes);
                for (ComplexTypeMetadata subType : referencedType.getSubTypes()) {
                    for (FieldMetadata field : subType.getFields()) {
                        if (field.getDeclaringType() == subType) {
                            _paths(subType, target, currentPath, foundPaths, processedTypes);
                        }
                    }
                }
            }
        }
        currentPath.pop();
    }
}

From source file:com.taobao.tdhs.jdbc.sqlparser.ParseSQL.java

public boolean checkRealEqual(Stack<String> stack) {
    logger.debug("checkRealEqual:" + stack.toString());
    String tmp_str = "";
    @SuppressWarnings("unchecked")
    Stack<String> tmpStack = (Stack<String>) stack.clone();
    while (tmpStack.isEmpty() == false) {
        tmp_str = tmpStack.pop() + tmp_str;
    }//from   w w w . j a va  2  s  .co  m

    //?',?,?,value
    boolean result = !checkSpecialStr(tmp_str, "'");
    logger.debug(result ? "=?" : "?=?");
    return result;
}