Example usage for java.util Stack peek

List of usage examples for java.util Stack peek

Introduction

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

Prototype

public synchronized E peek() 

Source Link

Document

Looks at the object at the top of this stack without removing it from the stack.

Usage

From source file:org.coursera.courier.lang.PoorMansCStyleSourceFormatter.java

public String format(String code) {
    String lines[] = code.split("\\r?\\n");
    StringBuilder result = new StringBuilder();
    Stack<Scope> scope = new Stack<>();
    scope.push(Scope.ROOT);/*from   ww  w .  j  a v a2  s.co  m*/

    int indentLevel = 0;
    boolean isPreviousLineEmpty = true;
    boolean isPreviousLinePreamble = false;

    for (String line : lines) {
        line = line.trim();

        // skip repeated empty lines
        boolean isEmpty = (line.length() == 0);
        if (isEmpty && ((isPreviousLineEmpty || isPreviousLinePreamble) || scope.size() > 2))
            continue;

        if (scope.peek() == Scope.COMMENT && line.startsWith("*")
                && docCommentStyle == DocCommentStyle.ASTRISK_MARGIN) {
            result.append(" "); // align javadoc continuation
        }

        if ((scope.peek() == Scope.BLOCK || scope.peek() == Scope.SWITCH) && line.startsWith("}")) {
            scope.pop();
            indentLevel--;
        } else if (scope.peek() == Scope.PARAMS && line.startsWith(")")) {
            scope.pop();
            indentLevel--;
        } else if (scope.peek() == Scope.COMMENT && line.startsWith("*/")) {
            scope.pop();
            if (docCommentStyle == DocCommentStyle.NO_MARGIN)
                indentLevel--;
        }

        boolean isCaseStmt = scope.peek() == Scope.SWITCH
                && (line.startsWith("case ") || line.startsWith("default"));

        boolean isDeclContinuation = line.startsWith("extends") || line.startsWith("with")
                || line.startsWith("implements");

        result.append(
                StringUtils.repeat(indent, indentLevel - (isCaseStmt ? 1 : 0) + (isDeclContinuation ? 1 : 0)));

        result.append(line);
        result.append('\n');

        if (line.endsWith("{")) {
            indentLevel++;
            if (line.startsWith("switch ")) {
                scope.push(Scope.SWITCH);
            } else {
                scope.push(Scope.BLOCK);
            }
        } else if (line.endsWith("(")) {
            indentLevel++;
            scope.push(Scope.PARAMS);
        } else if (line.startsWith("/**")) {
            scope.push(Scope.COMMENT);
            if (docCommentStyle == DocCommentStyle.NO_MARGIN)
                indentLevel++;
        }

        isPreviousLinePreamble = (line.startsWith("@") || line.startsWith("*"));
        isPreviousLineEmpty = isEmpty;
    }
    return result.toString();
}

From source file:eu.crisis_economics.abm.markets.clearing.IncrementalLoanDistributionAlgorithm.java

private Pair<Double, Double> distributeLoans(final Map<String, Borrower> borrowers,
        final Map<String, Lender> lenders, final Map<String, Double> loanDemands,
        final Map<String, Double> loanSupplies, final Map<Pair<String, String>, Double> interestRates) {

    // collect amount demanded by each firm at the current interest rate
    Map<String, Double> updatedLoanDemand = new HashMap<String, Double>();
    for (String key : loanDemands.keySet())
        updatedLoanDemand.put(key, 0.);//from   w  w w .  j  av  a  2  s .  c o  m

    Map<String, Double> updatedLoanSupply = new HashMap<String, Double>();
    Map<String, Double> loanSuppliesCopy = new HashMap<String, Double>();
    for (String key : loanSupplies.keySet()) {
        updatedLoanSupply.put(key, 0.);
        loanSuppliesCopy.put(key, loanSupplies.get(key));
    }

    /** 
      * Aggregation for loans. Loans between the same participant pair (the
      * same lender-borrower pair) will be combined, by extension of the loan
      * principal, until the cash aggreation threshold LOAN_AGGREGATION_THRESHOLD
      * is reached. At this point, a new loan contract will instead be created.
      */
    class LoanAggregator {
        private static final double LOAN_AGGREGATION_THRESHOLD = 5.e7;
        private Map<MultiKey<String>, Stack<Loan>> newLoanContracts = new HashMap<MultiKey<String>, Stack<Loan>>();

        // Establish a new effective loan, either (a) by creating a loan contract, or
        // (b) by extending the principal sum of an existing loan.
        void establishNew(String borrowerID, String lenderID, double principalValue) {
            MultiKey<String> contractKey = new MultiKey<String>(borrowerID, lenderID);
            Stack<Loan> existingLoans = newLoanContracts.get(contractKey);
            if (existingLoans == null) {
                existingLoans = new Stack<Loan>();
                newLoanContracts.put(contractKey, existingLoans);
                existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue));
            } else if (existingLoans.peek().getLoanPrincipalValue() < LOAN_AGGREGATION_THRESHOLD) {
                extendExistingLoan(existingLoans.peek(), principalValue);
            } else
                existingLoans.push(createNewLoan(borrowerID, lenderID, principalValue));
        }

        // Create a new loan contract.
        private Loan createNewLoan(String borrowerID, String lenderID, double principalValue) {
            return setupLoanContract(borrowers.get(borrowerID), lenders.get(lenderID), principalValue,
                    interestRates.get(new Pair<String, String>(borrowerID, lenderID)));
        }
    }
    LoanAggregator loanAggregator = new LoanAggregator();

    final Iterator<Entry<String, Double>> firmIter = loanDemands.entrySet().iterator();
    while (firmIter.hasNext()) {
        Entry<String, Double> firm = firmIter.next();
        final Iterator<Entry<String, Double>> bankIter = loanSuppliesCopy.entrySet().iterator();
        while (bankIter.hasNext()) {
            Entry<String, Double> bank = bankIter.next();
            // leverage circle in case lender == borrower's depositor - try same bank again
            while (updatedLoanDemand.get(firm.getKey()) < firm.getValue()
                    && updatedLoanSupply.get(bank.getKey()) < bank.getValue()) {
                double reserves = ((Bank) lenders.get(bank.getKey())).getCashReserveValue();
                if (reserves > 0.0) {
                    double increment = Math.min(reserves,
                            Math.min(firm.getValue() - updatedLoanDemand.get(firm.getKey()),
                                    bank.getValue() - updatedLoanSupply.get(bank.getKey())));
                    updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment);
                    updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment);
                    loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy
                    loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment);
                } else {
                    // leverage circle in case lender != borrower's depositor - try all (other) banks
                    final Iterator<Entry<String, Double>> otherBankIter = loanSuppliesCopy.entrySet()
                            .iterator();
                    while (otherBankIter.hasNext()) {
                        Entry<String, Double> otherBank = otherBankIter.next();
                        while (updatedLoanDemand.get(firm.getKey()) < firm.getValue()
                                && updatedLoanSupply.get(otherBank.getKey()) < otherBank.getValue()) {
                            reserves = ((Bank) lenders.get(otherBank.getKey())).getCashReserveValue();
                            if (reserves > 0.0) {
                                double increment = Math.min(reserves, Math.min(
                                        firm.getValue() - updatedLoanDemand.get(firm.getKey()),
                                        otherBank.getValue() - updatedLoanSupply.get(otherBank.getKey())));
                                updatedLoanDemand.put(firm.getKey(),
                                        updatedLoanDemand.get(firm.getKey()) + increment);
                                updatedLoanSupply.put(otherBank.getKey(),
                                        updatedLoanSupply.get(otherBank.getKey()) + increment);
                                loanSupplies.put(otherBank.getKey(),
                                        loanSupplies.get(otherBank.getKey()) - increment); //legacy
                                loanAggregator.establishNew(firm.getKey(), otherBank.getKey(), increment);
                            } else
                                break;
                        }
                        if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue())
                            break; // otherBank loop shortcut
                    }
                    // in case cash is not flowing back to any bank, bank has to handle cash flow exception
                    double increment = firm.getValue() - updatedLoanDemand.get(firm.getKey());
                    if (increment > 0) {
                        updatedLoanDemand.put(firm.getKey(), updatedLoanDemand.get(firm.getKey()) + increment);
                        updatedLoanSupply.put(bank.getKey(), updatedLoanSupply.get(bank.getKey()) + increment);
                        loanSupplies.put(bank.getKey(), loanSupplies.get(bank.getKey()) - increment); //legacy
                        loanAggregator.establishNew(firm.getKey(), bank.getKey(), increment);
                    }
                    break; // no point of trying same bank again
                }
            }
            if (updatedLoanDemand.get(firm.getKey()) >= firm.getValue())
                break; // bank loop shortcut
        }
    }

    double effectiveLoan = 0., tradeWeightedInterestRate = 0.;
    int numberOfLoansCreated = 0;
    for (Stack<Loan> loans : loanAggregator.newLoanContracts.values()) {
        for (Loan loan : loans) {
            effectiveLoan += loan.getLoanPrincipalValue();
            tradeWeightedInterestRate += loan.getLoanPrincipalValue() * loan.getInterestRate();
        }
        numberOfLoansCreated += loans.size();
    }
    System.out.println("Number of loans created: " + numberOfLoansCreated + ".");
    loanAggregator.newLoanContracts.clear();
    return new Pair<Double, Double>(effectiveLoan, tradeWeightedInterestRate / effectiveLoan);
}

From source file:org.freedesktop.mime.DefaultGlobService.java

/**
 * Converts a Unix-style glob to a regular expression.
 * <p>//from w  w  w.  j a v  a  2  s .  co m
 * ? becomes ., * becomes .*, {aa,bb} becomes (aa|bb).
 * 
 * @param glob
 *            The glob pattern
 */
public static String globToRE(String glob) {
    // TODO this is GPL code - replace
    final Object NEG = new Object();
    final Object GROUP = new Object();
    Stack<Object> state = new Stack<Object>();

    StringBuffer buf = new StringBuffer();
    boolean backslash = false;

    for (int i = 0; i < glob.length(); i++) {
        char c = glob.charAt(i);
        if (backslash) {
            buf.append('\\');
            buf.append(c);
            backslash = false;
            continue;
        }

        switch (c) {
        case '\\':
            backslash = true;
            break;
        case '?':
            buf.append('.');
            break;
        case '.':
        case '+':
        case '(':
        case ')':
            buf.append('\\');
            buf.append(c);
            break;
        case '*':
            buf.append(".*");
            break;
        case '|':
            if (backslash)
                buf.append("\\|");
            else
                buf.append('|');
            break;
        case '{':
            buf.append('(');
            if (i + 1 != glob.length() && glob.charAt(i + 1) == '!') {
                buf.append('?');
                state.push(NEG);
            } else
                state.push(GROUP);
            break;
        case ',':
            if (!state.isEmpty() && state.peek() == GROUP)
                buf.append('|');
            else
                buf.append(',');
            break;
        case '}':
            if (!state.isEmpty()) {
                buf.append(")");
                if (state.pop() == NEG)
                    buf.append(".*");
            } else
                buf.append('}');
            break;
        default:
            buf.append(c);
        }
    }

    return buf.toString();
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Insert the line-start and end for an internal lineformat
 * @param stack the tag stack to tell us the depth
 *///from www .ja v a 2 s.c  o m
void startPreLine(Stack<EndTag> stack) {
    JSONObject lf = stack.peek().def;
    String pre = (String) lf.get("leftTag");
    String post = (String) lf.get("rightTag");
    mml.append(post);
    mml.append("\n");
    mml.append(pre);
}

From source file:edu.mit.lib.tools.Modernize.java

public void importToMds(String targetUrl) throws IOException {
    if (manif.isEmpty()) {
        manif.read();//from   w w  w  .  j  a  v  a2 s .c o m
    }
    Stack<String> parents = new Stack<>();
    parents.push(null); // indicates no parent object

    for (int i = 0; i < manif.entries.size(); i++) {
        String handle = manif.entries.get(i);
        uploadPackage(getPackage(handle), getPostUrl(targetUrl, parents.peek(), manif.ctypes.get(i)));
        if (i < manif.entries.size() - 1) {
            int diff = manif.levels.get(i) - manif.levels.get(i + 1);
            if (diff < 0) {
                // I have kids - put myself on the parents stack
                parents.push(handle);
            } else if (diff > 0) {
                // expose grandparents
                while (diff-- > 0) {
                    parents.pop();
                }
            } // if diff == 0 - next entry is a sibling, nothing to do
        }
    }
}

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()));
            }//  w  w w  .j  a  v  a  2 s .  com
        }

        //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:org.openvpms.tools.data.loader.DataLoader.java

/**
 * Starts a data element, pushing it on the stack.
 *
 * @param reader the reader//from   w w w . j  a  va 2  s  .  co m
 * @param stack  the stack of load states
 * @param path   a path representing the stream source, for logging purposes
 */
private void startData(XMLStreamReader reader, Stack<LoadState> stack, String path) {
    LoadState current;
    Data data = new Data(reader);
    if (verbose) {
        String archetypeId = stack.isEmpty() ? "none" : stack.peek().getArchetypeId().toString();
        log.info("[START PROCESSING element, parent=" + archetypeId + "]" + data);
    }

    try {
        if (!stack.isEmpty()) {
            current = processData(stack.peek(), data, path);
        } else {
            current = processData(null, data, path);
        }
        stack.push(current);
    } catch (Exception exception) {
        Location location = reader.getLocation();
        log.error("Error in start element, line " + location.getLineNumber() + ", column "
                + location.getColumnNumber() + "" + data + "", exception);
    }
}

From source file:ParenMatcher.java

public void run() {
    StyledDocument doc = getStyledDocument();
    String text = "";
    int len = doc.getLength();
    try {/*from w  w w  .ja  va 2  s . c  om*/
        text = doc.getText(0, len);
    } catch (BadLocationException ble) {
    }
    java.util.Stack stack = new java.util.Stack();
    for (int j = 0; j < text.length(); j += 1) {
        char ch = text.charAt(j);
        if (ch == '(' || ch == '[' || ch == '{') {
            int depth = stack.size();
            stack.push("" + ch + j); // push a String containg the char and
            // the offset
            AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
            doc.setCharacterAttributes(j, 1, aset, false);
        }
        if (ch == ')' || ch == ']' || ch == '}') {
            String peek = stack.empty() ? "." : (String) stack.peek();
            if (matches(peek.charAt(0), ch)) { // does it match?
                stack.pop();
                int depth = stack.size();
                AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
                doc.setCharacterAttributes(j, 1, aset, false);
            } else { // mismatch
                doc.setCharacterAttributes(j, 1, badAttrSet, false);
            }
        }
    }

    while (!stack.empty()) { // anything left in the stack is a mismatch
        String pop = (String) stack.pop();
        int offset = Integer.parseInt(pop.substring(1));
        doc.setCharacterAttributes(offset, 1, badAttrSet, false);
    }
}

From source file:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under Self Service -> Faculty Center -> My
 * Schedule on GET. A sample record is as follows:
 * "Doe,John M 302043188 3.00 Engr, Comp Sci, & Tech  CS MS". Again, not all
 * fields may be present.//from w  ww  . ja  va 2  s .co m
 */
private List<ImportedUser> parse2(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();
    Stack<String> stack = new Stack<String>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String name = "";
        do {
            String token = scanner.next();
            if (!isName(token))
                stack.push(token);
            else {
                name = token;
                while (!stack.isEmpty() && !isDegree(stack.peek()))
                    name = stack.pop() + " " + name;
                break;
            }
        } while (scanner.hasNext());

        String cin = "";
        boolean cinFound = false;
        while (scanner.hasNext()) {
            cin = scanner.next();
            if (isCin(cin)) {
                cinFound = true;
                break;
            } else
                name += " " + cin;
        }

        if (cinFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

From source file:org.jbpm.JbpmConfiguration.java

public JbpmContext getCurrentJbpmContext() {
    JbpmContext currentJbpmContext = null;
    Stack stack = getJbpmContextStack();
    if (!stack.isEmpty()) {
        currentJbpmContext = (JbpmContext) stack.peek();
    }/*from w w w  . j  ava  2  s  . co m*/
    return currentJbpmContext;
}