List of usage examples for java.util Stack push
public E push(E item)
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 www . j a va2 s. co 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:geva.Mapper.GEGrammar.java
String generateNameFromTree(DerivationTree tree) { StringBuilder builder = new StringBuilder(); Stack<DerivationNode> nodeStack = new Stack<DerivationNode>(); nodeStack.push((DerivationNode) tree.getRoot()); while (nodeStack.empty() == false) { DerivationNode nodes = nodeStack.pop(); if (nodes != null) { if (nodes.getCodonIndex() != -1) { builder.append(nodes.getCodonPick()); }//w w w .j a va2s . co m if (nodes.size() != 0) { builder.append('['); nodeStack.push(null); for (int i = nodes.size(); i > 0; i--) { nodeStack.push((DerivationNode) nodes.get(i - 1)); } } } else { builder.append(']'); } } return builder.toString(); }
From source file:com.marklogic.contentpump.AggregateXMLReader.java
protected void copyNameSpaceDecl() { if (recordDepth < currDepth) { return;/*w ww.ja v a 2 s.c o m*/ } int stop = xmlSR.getNamespaceCount(); if (stop > 0) { String nsDeclPrefix, nsDeclUri; if (LOG.isTraceEnabled()) { LOG.trace("checking namespace declarations"); } for (int i = 0; i < stop; i++) { nsDeclPrefix = xmlSR.getNamespacePrefix(i); nsDeclUri = xmlSR.getNamespaceURI(i); if (LOG.isTraceEnabled()) { LOG.trace(nsDeclPrefix + ":" + nsDeclUri); } if (nameSpaces.containsKey(nsDeclPrefix)) { nameSpaces.get(nsDeclPrefix).push(nsDeclUri); } else { Stack<String> s = new Stack<String>(); s.push(nsDeclUri); nameSpaces.put(nsDeclPrefix, s); } } } }
From source file:com.autentia.intra.bean.MenuBean.java
/** * Get menu tree/* w w w . j ava 2 s . c om*/ * * @return menu tree */ public TreeNode getMenu() { // Create menu only the first time if (menu == null) { Principal creds = SpringUtils.getPrincipal(); Stack<TreeNode> path = new Stack<TreeNode>(); menu = new TreeNodeBase("menu", "Menu", false); path.push(menu); if (openNode(path, creds, null, "admin")) { addLeaf(path, creds, Permission.Entity_Menu(User.class), "users"); addLeaf(path, creds, Permission.Entity_Menu(UserCategory.class), "userCategorys"); addLeaf(path, creds, null, "changePassword"); addLeaf(path, creds, Permission.Entity_Menu(Department.class), "departments"); // addLeaf( path, creds, Permission.Entity_Menu(Setting.class), "settings" ); closeNode(path); } if (openNode(path, creds, null, "masterTables")) { addLeaf(path, creds, Permission.Entity_Menu(AccountEntryType.class), "accountEntryTypes"); addLeaf(path, creds, Permission.Entity_Menu(OrganizationType.class), "organizationTypes"); addLeaf(path, creds, Permission.Entity_Menu(InteractionType.class), "interactionTypes"); addLeaf(path, creds, Permission.Entity_Menu(OrganizationISOCategory.class), "organizationISOCategorys"); addLeaf(path, creds, Permission.Entity_Menu(ContractType.class), "contractTypes"); addLeaf(path, creds, Permission.Entity_Menu(Magazine.class), "magazines"); addLeaf(path, creds, Permission.Entity_Menu(OfferRejectReason.class), "offerRejectReasons"); closeNode(path); } if (openNode(path, creds, null, "billing")) { addLeaf(path, creds, Permission.Entity_Menu(Bill.class), "bills"); addLeaf(path, creds, Permission.Entity_Menu(Account.class), "accounts"); addLeaf(path, creds, Permission.Entity_Menu(AccountEntry.class), "accountEntrys"); addLeaf(path, creds, Permission.Entity_Menu(PeriodicalAccountEntry.class), "periodicalAccountEntrys"); addLeaf(path, creds, Permission.Action_NOF, "nof"); addLeaf(path, creds, Permission.Entity_Menu(FinancialRatio.class), "financialRatios"); closeNode(path); } if (openNode(path, creds, null, "contacts")) { addLeaf(path, creds, Permission.Entity_Menu(Organization.class), "organizations"); addLeaf(path, creds, Permission.Entity_Menu(Interaction.class), "interactions"); addLeaf(path, creds, Permission.Entity_Menu(Contact.class), "contacts"); addLeaf(path, creds, Permission.Entity_Menu(Offer.class), "offers"); addLeaf(path, creds, Permission.Entity_Menu(Project.class), "projects"); closeNode(path); } if (openNode(path, creds, null, "quality")) { addLeaf(path, creds, Permission.Action_ListQualityDocuments, "qualityDocuments"); closeNode(path); } if (openNode(path, creds, null, "bulletin")) { addLeaf(path, creds, Permission.Entity_Menu(BulletinBoard.class), "bulletinBoards"); addLeaf(path, creds, Permission.Entity_Menu(CompanyState.class), "companyStates"); addLeaf(path, creds, Permission.Entity_Menu(BulletinBoardCategory.class), "bulletinBoardCategorys"); addLeaf(path, creds, Permission.Entity_Menu(Idea.class), "ideas"); closeNode(path); } if (openNode(path, creds, null, "activity")) { addLeaf(path, creds, Permission.Entity_Menu(Activity.class), "activitys"); addLeaf(path, creds, Permission.Entity_Menu(Objective.class), "objectives"); closeNode(path); } if (openNode(path, creds, null, "reports")) { addLeaf(path, creds, Permission.Action_GeneralReports, "generalReports"); addLeaf(path, creds, Permission.Action_BitacoreReports, "bitacoreReports"); addLeaf(path, creds, Permission.Action_BillReports, "billReports"); addLeaf(path, creds, Permission.Action_ProjectReports, "projectReports"); addLeaf(path, creds, Permission.Action_InteractionReports, "interactionReports"); addLeaf(path, creds, Permission.Action_OrganizationReports, "organizationReports"); addLeaf(path, creds, Permission.Action_OfferReports, "offerReports"); addLeaf(path, creds, Permission.Action_PersonalReports, "personalReports"); closeNode(path); } if (openNode(path, creds, null, "publish")) { addLeaf(path, creds, Permission.Entity_Menu(Tutorial.class), "tutorials"); addLeaf(path, creds, Permission.Entity_Menu(Publication.class), "publications"); closeNode(path); } if (openNode(path, creds, null, "holiday")) { addLeaf(path, creds, Permission.Entity_Menu(Holiday.class), "holidays"); addLeaf(path, creds, Permission.Entity_Menu(RequestHoliday.class), "requestHolidays"); addLeaf(path, creds, Permission.Entity_Menu(AdminHoliday.class), "adminHolidays"); closeNode(path); } if (openNode(path, creds, null, "utils")) { addLeaf(path, creds, Permission.Entity_Menu(Book.class), "books"); addLeaf(path, creds, Permission.Entity_Menu(Inventary.class), "inventarys"); closeNode(path); } } return menu; }
From source file:alluxio.underfs.hdfs.HdfsUnderFileSystem.java
@Override public boolean mkdirs(String path, MkdirsOptions options) throws IOException { IOException te = null;/*from w w w.j av a2 s. c o m*/ RetryPolicy retryPolicy = new CountingRetry(MAX_TRY); while (retryPolicy.attemptRetry()) { try { Path hdfsPath = new Path(path); if (mFileSystem.exists(hdfsPath)) { LOG.debug("Trying to create existing directory at {}", path); return false; } // Create directories one by one with explicit permissions to ensure no umask is applied, // using mkdirs will apply the permission only to the last directory Stack<Path> dirsToMake = new Stack<>(); dirsToMake.push(hdfsPath); Path parent = hdfsPath.getParent(); while (!mFileSystem.exists(parent)) { dirsToMake.push(parent); parent = parent.getParent(); } while (!dirsToMake.empty()) { Path dirToMake = dirsToMake.pop(); if (!FileSystem.mkdirs(mFileSystem, dirToMake, new FsPermission(options.getMode().toShort()))) { return false; } // Set the owner to the Alluxio client user to achieve permission delegation. // Alluxio server-side user is required to be a HDFS superuser. If it fails to set owner, // proceeds with mkdirs and print out an warning message. try { setOwner(dirToMake.toString(), options.getOwner(), options.getGroup()); } catch (IOException e) { LOG.warn("Failed to update the ufs dir ownership, default values will be used. " + e); } } return true; } catch (IOException e) { LOG.warn("{} try to make directory for {} : {}", retryPolicy.getRetryCount(), path, e.getMessage()); te = e; } } throw te; }
From source file:edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizerImpl.java
/** * Build a tree for a digital object id from a list of DataOrganizationNode * obtained from a data source.//ww w . j a va2s . c o m * * @param nodes The list of nodes. * @param digitalObjectID The digital object id the tree is associated with. * * @return The tree. */ private FileTree buildTree(List<DataOrganizationNode> nodes, DigitalObjectId digitalObjectID) { FileTree tree = null; if (!nodes.isEmpty()) { Stack<DataOrganizationNode> stack = new Stack<>(); DataOrganizationNode node = nodes.get(0); if (!(node instanceof CollectionNode)) { return null; } tree = new FileTree((CollectionNode) node); tree.setDigitalObjectId(digitalObjectID); node = tree; stack.push(node); DataOrganizationNode nextNode; for (int i = 1; i < nodes.size(); ++i) { nextNode = nodes.get(i); while (stack.peek().getStepNoLeaved() < nextNode.getStepNoLeaved()) { stack.pop(); } node = stack.peek(); ((CollectionNode) node).addChild(nextNode); stack.push(nextNode); } } return tree; }
From source file:com.autentia.tnt.bean.MenuBean.java
/** * Get menu tree//from w ww. j a v a 2 s.c om * @return menu tree */ public TreeNode getMenu() { // Create menu only the first time if (menu == null) { Principal creds = SpringUtils.getPrincipal(); Stack<TreeNode> path = new Stack<TreeNode>(); menu = new TreeNodeBase("menu", "Menu", false); path.push(menu); if (openNode(path, creds, null, "admin")) { addLeaf(path, creds, Permission.Entity_Menu(User.class), "users"); addLeaf(path, creds, Permission.Entity_Menu(UserCategory.class), "userCategorys"); addLeaf(path, creds, null, "changePassword"); addLeaf(path, creds, Permission.Entity_Menu(Department.class), "departments"); // addLeaf( path, creds, Permission.Entity_Menu(Setting.class), "settings" ); closeNode(path); } if (openNode(path, creds, null, "masterTables")) { addLeaf(path, creds, Permission.Entity_Menu(AccountEntryType.class), "accountEntryTypes"); addLeaf(path, creds, Permission.Entity_Menu(OrganizationType.class), "organizationTypes"); addLeaf(path, creds, Permission.Entity_Menu(InteractionType.class), "interactionTypes"); addLeaf(path, creds, Permission.Entity_Menu(OrganizationISOCategory.class), "organizationISOCategorys"); addLeaf(path, creds, Permission.Entity_Menu(ContractType.class), "contractTypes"); addLeaf(path, creds, Permission.Entity_Menu(Magazine.class), "magazines"); addLeaf(path, creds, Permission.Entity_Menu(OfferRejectReason.class), "offerRejectReasons"); closeNode(path); } if (openNode(path, creds, null, "billing")) { addLeaf(path, creds, Permission.Entity_Menu(Bill.class), "bills"); addLeaf(path, creds, Permission.Entity_Menu(Account.class), "accounts"); addLeaf(path, creds, Permission.Entity_Menu(AccountEntry.class), "accountEntrys"); addLeaf(path, creds, Permission.Entity_Menu(PeriodicalAccountEntry.class), "periodicalAccountEntrys"); addLeaf(path, creds, Permission.Action_NOF, "nof"); addLeaf(path, creds, Permission.Entity_Menu(FinancialRatio.class), "financialRatios"); closeNode(path); } if (openNode(path, creds, null, "contacts")) { addLeaf(path, creds, Permission.Entity_Menu(Organization.class), "organizations"); addLeaf(path, creds, Permission.Entity_Menu(Interaction.class), "interactions"); addLeaf(path, creds, Permission.Entity_Menu(Contact.class), "contacts"); addLeaf(path, creds, Permission.Entity_Menu(Offer.class), "offers"); addLeaf(path, creds, Permission.Entity_Menu(Project.class), "projects"); closeNode(path); } if (openNode(path, creds, null, "quality")) { addLeaf(path, creds, Permission.Action_ListQualityDocuments, "qualityDocuments"); closeNode(path); } if (openNode(path, creds, null, "bulletin")) { addLeaf(path, creds, Permission.Entity_Menu(BulletinBoard.class), "bulletinBoards"); addLeaf(path, creds, Permission.Entity_Menu(CompanyState.class), "companyStates"); addLeaf(path, creds, Permission.Entity_Menu(BulletinBoardCategory.class), "bulletinBoardCategorys"); addLeaf(path, creds, Permission.Entity_Menu(Idea.class), "ideas"); closeNode(path); } if (openNode(path, creds, null, "activity")) { addLeaf(path, creds, Permission.Entity_Menu(Activity.class), "activitys"); addLeaf(path, creds, Permission.Entity_Menu(Objective.class), "objectives"); closeNode(path); } if (openNode(path, creds, null, "reports")) { addLeaf(path, creds, Permission.Action_GeneralReports, "generalReports"); addLeaf(path, creds, Permission.Action_BitacoreReports, "bitacoreReports"); addLeaf(path, creds, Permission.Action_BillReports, "billReports"); addLeaf(path, creds, Permission.Action_ProjectReports, "projectReports"); addLeaf(path, creds, Permission.Action_InteractionReports, "interactionReports"); addLeaf(path, creds, Permission.Action_OrganizationReports, "organizationReports"); addLeaf(path, creds, Permission.Action_OfferReports, "offerReports"); addLeaf(path, creds, Permission.Action_OwnReports, "ownReports"); addLeaf(path, creds, Permission.Action_PersonalReports, "personalReports"); closeNode(path); } if (openNode(path, creds, null, "publish")) { addLeaf(path, creds, Permission.Entity_Menu(Tutorial.class), "tutorials"); addLeaf(path, creds, Permission.Entity_Menu(Publication.class), "publications"); closeNode(path); } if (openNode(path, creds, null, "holiday")) { addLeaf(path, creds, Permission.Entity_Menu(Holiday.class), "holidays"); addLeaf(path, creds, Permission.Entity_Menu(RequestHoliday.class), "requestHolidays"); addLeaf(path, creds, Permission.Entity_Menu(AdminHoliday.class), "adminHolidays"); closeNode(path); } if (openNode(path, creds, null, "utils")) { addLeaf(path, creds, Permission.Entity_Menu(Book.class), "books"); addLeaf(path, creds, Permission.Entity_Menu(Inventary.class), "inventarys"); closeNode(path); } } return menu; }
From source file:ch.entwine.weblounge.contentrepository.impl.fs.FileSystemContentRepository.java
/** * {@inheritDoc}//w w w. j a v a 2s .com * * @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#listResources() */ @Override protected Collection<ResourceURI> listResources() throws IOException { List<ResourceURI> uris = new ArrayList<ResourceURI>(); // Add all known resource types to the index for (ResourceSerializer<?, ?> serializer : getSerializers()) { // Temporary path for rebuilt site String resourceType = serializer.getType().toLowerCase(); String resourceDirectory = resourceType + "s"; String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory); File resourcesRootDirectory = new File(homePath); if (!resourcesRootDirectory.isDirectory() || resourcesRootDirectory.list().length == 0) { logger.debug("No {}s found to index", resourceType); continue; } try { Stack<File> u = new Stack<File>(); u.push(resourcesRootDirectory); while (!u.empty()) { File dir = u.pop(); File[] files = dir.listFiles(new FileFilter() { public boolean accept(File path) { if (path.getName().startsWith(".")) return false; return path.isDirectory() || path.getName().endsWith(".xml"); } }); if (files == null || files.length == 0) continue; for (File f : files) { if (f.isDirectory()) { u.push(f); } else { long version = Long.parseLong(f.getParentFile().getName()); String id = f.getParentFile().getParentFile().getName(); ResourceURI uri = new ResourceURIImpl(resourceType, getSite(), null, id, version); uris.add(uri); } } } } catch (Throwable t) { logger.error("Error reading available uris from file system: {}", t.getMessage()); throw new IOException(t); } } return uris; }
From source file:com.glaf.core.service.impl.MxQueryDefinitionServiceImpl.java
private void loadQueryDefinitionStack(Stack<QueryDefinition> stack, QueryDefinition query) { if (query != null && query.getParentId() != null) { QueryDefinition parent = this.getQueryDefinition(query.getParentId()); if (parent != null) { query.setParent(parent);/*w ww . java 2 s .c om*/ parent.setChild(query); stack.push(parent); this.loadQueryDefinitionStack(stack, parent); } } }
From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java
public String[] searchPrefix(String prefix) { Set<String> results = new HashSet<String>(); if ((prefix == null) || (prefix.length() < 2)) return results.toArray(new String[results.size()]); char[] letters = prefix.toUpperCase().toCharArray(); long ptr = nodes[0]; for (char c : letters) { ptr = findChild(ptr, c);/* w w w. j a v a 2 s. c om*/ if (-1 == ptr) return results.toArray(new String[results.size()]); } // iteratively (to prevent stack overflow) search each branch of the graph Stack<StackEntry> stack = new Stack<StackEntry>(); // a stack of paths to traverse. This prevents the StackOverflowException. stack.push(new StackEntry(ptr, prefix.toUpperCase().toCharArray(), "")); while (!stack.empty()) { StackEntry entry = stack.pop(); // if current node is a valid word if (canTerminate(entry.node)) { results.add(String.valueOf(entry.chars) + entry.subword); } for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) { long child = iter.next(); stack.push(new StackEntry(child, entry.chars, entry.subword + getChar(child))); } } return results.toArray(new String[results.size()]); }