Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

In this page you can find the example usage for java.math BigDecimal divide.

Prototype

public BigDecimal divide(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

From source file:org.egov.works.web.actions.estimate.EstimatePDFGenerator.java

private PdfPTable createBudgetaryAppropriationTable(final AbstractEstimate estimate,
        final String appropriationNumber) throws DocumentException {
    int isReject = -1;
    final List<FinancialDetail> financialdetails = estimate.getFinancialDetails();
    BigDecimal totalGrant;/*from  www.  jav  a  2 s  .co  m*/
    BigDecimal budgetAvailable;
    BigDecimal balOnHand;
    BigDecimal amtAppropriated;
    BigDecimal totGrantafterMultiFactor = BigDecimal.ZERO;

    estimateAppropriationService = abstractEstimateService.getEstimateAppropriationService();
    abstractEstimateAppropriationList = estimateAppropriationService.findAllBy(
            "from AbstractEstimateAppropriation aea where aea.abstractEstimate.id=? and aea.budgetUsage.id is not null order by aea.budgetUsage.id,aea.budgetUsage.financialYearId asc",
            estimate.getId());

    final PdfPTable budgetaryAppropriationTable = new PdfPTable(1);
    budgetaryAppropriationTable.setWidthPercentage(100);
    budgetaryAppropriationTable.setWidths(new float[] { 8f });
    if (appropriationNumber != null && appropriationNumber.toUpperCase().contains("BC"))
        isReject = 1;

    if (appropriationNumber != null && estimate.getTotalAmount() != null && isReject == -1)
        for (final FinancialDetail financialDetail : financialdetails)
            if (financialDetail.getBudgetGroup() != null) {
                addRow(budgetaryAppropriationTable, true, centerPara("Budget Head"),
                        centerPara(financialDetail.getBudgetGroup().getName()));
                addRow(budgetaryAppropriationTable, true, makePara("Function Center"),
                        centerPara(financialDetail.getFunction().getName()));
                addRow(budgetaryAppropriationTable, true, makePara("Amount of the Estimate "),
                        rightPara(toCurrency(estimate.getTotalAmount())));
            }
    final PdfPTable appropriationDetailTable = new PdfPTable(8);
    int count = 0;
    for (final AbstractEstimateAppropriation abstractEstimateAppropriation : abstractEstimateAppropriationList)
        if (abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount() != 0) {
            final Department dept = getDeptFromBudgtAppropriationNo(
                    abstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber());
            totalGrant = abstractEstimateService.getTotalGrantForYearAsOnDate(financialdetails.get(0),
                    abstractEstimateAppropriation.getBudgetUsage().getFinancialYearId().longValue(),
                    Integer.parseInt(dept.getId().toString()),
                    abstractEstimateAppropriation.getBudgetUsage().getUpdatedTime());
            final BigDecimal planningBudgetPerc = abstractEstimateService.getPlanningBudgetPercentage(
                    financialdetails.get(0),
                    abstractEstimateAppropriation.getBudgetUsage().getFinancialYearId().longValue(),
                    Integer.parseInt(dept.getId().toString()));
            if (planningBudgetPerc != null && planningBudgetPerc.compareTo(BigDecimal.ZERO) != 0) {
                totGrantafterMultiFactor = totalGrant.multiply(planningBudgetPerc.divide(new BigDecimal(100)));
                appValue = planningBudgetPerc.divide(new BigDecimal(100)).toString();
            }
            budgetAvailable = abstractEstimateAppropriation.getBalanceAvailable();
            balOnHand = budgetAvailable
                    .add(new BigDecimal(abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount()));
            amtAppropriated = totGrantafterMultiFactor.subtract(balOnHand);
            // Print only for the first time
            if (count == 0) {
                addRow(budgetaryAppropriationTable, false, makePara(""),
                        centerPara("Financial Year Wise Appropriation Details "));
                addRow(appropriationDetailTable, true, makePara(8f, "Department"),
                        makePara(8f, "Appropriation Number"), makePara(8f, "Total Grant"),
                        makePara(8f, appValue + " Times Total Grant"),
                        makePara(8f, "Amount Appropriated so far"), makePara(8f, "Amount Appropriated"),
                        makePara(8f, "Balance on Hand"), makePara(8f, "Balance After Appropriation"));
            }
            addRow(appropriationDetailTable, true, rightPara(8f, dept.getName()),
                    makePara(8f, abstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber()),
                    rightPara(8f, toCurrency(totalGrant.doubleValue())),
                    rightPara(8f, toCurrency(totGrantafterMultiFactor.doubleValue())),
                    rightPara(8f, toCurrency(amtAppropriated.doubleValue())),
                    rightPara(8f,
                            toCurrency(abstractEstimateAppropriation.getBudgetUsage().getConsumedAmount())),
                    rightPara(8f, toCurrency(balOnHand.doubleValue())),
                    rightPara(8f, toCurrency(budgetAvailable.doubleValue())));
            count++;
        }

    final PdfPCell appDetailpdfCell = new PdfPCell(appropriationDetailTable);
    appropriationDetailTable.setWidthPercentage(100);
    budgetaryAppropriationTable.addCell(appDetailpdfCell);
    return budgetaryAppropriationTable;
}

From source file:org.kuali.ole.gl.batch.service.impl.PosterServiceImpl.java

/**
 * Generate a transfer transaction and an offset transaction
 * /*from  w  w w  .  j a  va2 s  .c o m*/
 * @param et an expenditure transaction
 * @param icrEntry the indirect cost recovery entry
 * @param generatedTransactionAmount the amount of the transaction
 * @param runDate the transaction date for the newly created origin entry
 * @param group the group to save the origin entry to
 */
protected void generateTransactions(ExpenditureTransaction et, IndirectCostRecoveryRateDetail icrRateDetail,
        KualiDecimal generatedTransactionAmount, Date runDate, PrintStream group,
        IndirectCostRecoveryGenerationMetadata icrGenerationMetadata) {

    BigDecimal pct = new BigDecimal(icrRateDetail.getAwardIndrCostRcvyRatePct().toString());
    pct = pct.divide(BDONEHUNDRED);

    OriginEntryFull e = new OriginEntryFull();
    e.setTransactionLedgerEntrySequenceNumber(0);

    // SYMBOL_USE_EXPENDITURE_ENTRY means we use the field from the expenditure entry, SYMBOL_USE_IRC_FROM_ACCOUNT
    // means we use the ICR field from the account record, otherwise, use the field in the icrRateDetail
    if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY
            .equals(icrRateDetail.getFinancialObjectCode())
            || GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT
                    .equals(icrRateDetail.getFinancialObjectCode())) {
        e.setFinancialObjectCode(et.getObjectCode());
        e.setFinancialSubObjectCode(et.getSubObjectCode());
    } else {
        e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode());
        e.setFinancialSubObjectCode(icrRateDetail.getFinancialSubObjectCode());
    }

    if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY
            .equals(icrRateDetail.getAccountNumber())) {
        e.setAccountNumber(et.getAccountNumber());
        e.setChartOfAccountsCode(et.getChartOfAccountsCode());
        e.setSubAccountNumber(et.getSubAccountNumber());
    } else if (GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT
            .equals(icrRateDetail.getAccountNumber())) {
        e.setAccountNumber(icrGenerationMetadata.getIndirectCostRecoveryAcctNbr());
        e.setChartOfAccountsCode(icrGenerationMetadata.getIndirectCostRcvyFinCoaCode());
        e.setSubAccountNumber(OLEConstants.getDashSubAccountNumber());
    } else {
        e.setAccountNumber(icrRateDetail.getAccountNumber());
        e.setSubAccountNumber(icrRateDetail.getSubAccountNumber());
        e.setChartOfAccountsCode(icrRateDetail.getChartOfAccountsCode());
        // TODO Reporting thing line 1946
    }
    // take care of infinite recursive error case - do not generate entries
    if ((et.getAccountNumber().equals(e.getAccountNumber()))
            && (et.getChartOfAccountsCode().equals(e.getChartOfAccountsCode()))
            && (et.getSubAccountNumber().equals(e.getSubAccountNumber()))
            && (et.getObjectCode().equals(e.getFinancialObjectCode()))
            && (et.getSubObjectCode().equals(e.getFinancialSubObjectCode()))) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(new Message("Infinite recursive encumbrance error " + et.getChartOfAccountsCode() + " "
                + et.getAccountNumber() + " " + et.getSubAccountNumber() + " " + et.getObjectCode() + " "
                + et.getSubObjectCode(), Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);
        return;
    }

    e.setFinancialDocumentTypeCode(
            parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class,
                    OLEConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY));
    e.setFinancialSystemOriginationCode(
            parameterService.getParameterValueAsString(OleParameterConstants.GENERAL_LEDGER_BATCH.class,
                    OLEConstants.SystemGroupParameterNames.GL_ORIGINATION_CODE));
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STRING);
    e.setDocumentNumber(sdf.format(runDate));
    if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
        e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(),
                icrGenerationMetadata.getIndirectCostRecoveryTypeCode(),
                et.getAccountObjectDirectCostAmount().abs()));
    } else {
        e.setTransactionLedgerEntryDescription(
                getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(),
                        et.getChartOfAccountsCode(), et.getAccountNumber()));
    }
    e.setTransactionDate(new java.sql.Date(runDate.getTime()));
    e.setTransactionDebitCreditCode(icrRateDetail.getTransactionDebitIndicator());
    e.setFinancialBalanceTypeCode(et.getBalanceTypeCode());
    e.setUniversityFiscalYear(et.getUniversityFiscalYear());
    e.setUniversityFiscalPeriodCode(et.getUniversityFiscalAccountingPeriod());

    ObjectCode oc = objectCodeService.getByPrimaryId(e.getUniversityFiscalYear(), e.getChartOfAccountsCode(),
            e.getFinancialObjectCode());
    if (oc == null) {
        LOG.warn(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND_FOR)
                + e.getUniversityFiscalYear() + "," + e.getChartOfAccountsCode() + ","
                + e.getFinancialObjectCode());
        e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode()); // this will be written out the ICR file. Then, when that file attempts to post, the transaction won't validate and will end up in the icr error file
    } else {
        e.setFinancialObjectTypeCode(oc.getFinancialObjectTypeCode());
    }

    if (generatedTransactionAmount.isNegative()) {
        if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
            e.setTransactionDebitCreditCode(OLEConstants.GL_CREDIT_CODE);
        } else {
            e.setTransactionDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
        }
        e.setTransactionLedgerEntryAmount(generatedTransactionAmount.negated());
    } else {
        e.setTransactionLedgerEntryAmount(generatedTransactionAmount);
    }

    if (et.getBalanceTypeCode().equals(et.getOption().getExtrnlEncumFinBalanceTypCd())
            || et.getBalanceTypeCode().equals(et.getOption().getIntrnlEncumFinBalanceTypCd())
            || et.getBalanceTypeCode().equals(et.getOption().getPreencumbranceFinBalTypeCd())
            || et.getBalanceTypeCode().equals(et.getOption().getCostShareEncumbranceBalanceTypeCd())) {
        e.setDocumentNumber(
                parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class,
                        OLEConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY));
    }
    e.setProjectCode(et.getProjectCode());
    if (GeneralLedgerConstants.getDashOrganizationReferenceId().equals(et.getOrganizationReferenceId())) {
        e.setOrganizationReferenceId(null);
    } else {
        e.setOrganizationReferenceId(et.getOrganizationReferenceId());
    }
    // TODO 2031-2039
    try {
        createOutputEntry(e, group);
    } catch (IOException ioe) {
        LOG.error("generateTransactions Stopped: " + ioe.getMessage());
        throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe);
    }

    // Now generate Offset
    e = new OriginEntryFull(e);
    if (OLEConstants.GL_DEBIT_CODE.equals(e.getTransactionDebitCreditCode())) {
        e.setTransactionDebitCreditCode(OLEConstants.GL_CREDIT_CODE);
    } else {
        e.setTransactionDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
    }
    e.setFinancialSubObjectCode(OLEConstants.getDashFinancialSubObjectCode());

    String offsetBalanceSheetObjectCodeNumber = determineIcrOffsetBalanceSheetObjectCodeNumber(e, et,
            icrRateDetail);
    e.setFinancialObjectCode(offsetBalanceSheetObjectCodeNumber);
    ObjectCode balSheetObjectCode = objectCodeService.getByPrimaryId(icrRateDetail.getUniversityFiscalYear(),
            e.getChartOfAccountsCode(), offsetBalanceSheetObjectCodeNumber);
    if (balSheetObjectCode == null) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(new Message(
                configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_INVALID_OFFSET_OBJECT_CODE)
                        + icrRateDetail.getUniversityFiscalYear() + "-" + e.getChartOfAccountsCode() + "-"
                        + offsetBalanceSheetObjectCodeNumber,
                Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);

    } else {
        e.setFinancialObjectTypeCode(balSheetObjectCode.getFinancialObjectTypeCode());
    }

    if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
        e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(),
                icrGenerationMetadata.getIndirectCostRecoveryTypeCode(),
                et.getAccountObjectDirectCostAmount().abs()));
    } else {
        e.setTransactionLedgerEntryDescription(
                getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(),
                        et.getChartOfAccountsCode(), et.getAccountNumber()));
    }

    try {
        flexibleOffsetAccountService.updateOffset(e);
    } catch (InvalidFlexibleOffsetException ex) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(
                new Message("FAILED TO GENERATE FLEXIBLE OFFSETS " + ex.getMessage(), Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);
        LOG.warn("FAILED TO GENERATE FLEXIBLE OFFSETS FOR EXPENDITURE TRANSACTION " + et.toString(), ex);
    }

    try {
        createOutputEntry(e, group);
    } catch (IOException ioe) {
        LOG.error("generateTransactions Stopped: " + ioe.getMessage());
        throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe);
    }
}

From source file:piuk.blockchain.android.ui.SendCoinsFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final SendCoinsActivity activity = (SendCoinsActivity) getActivity();

    final View view = inflater.inflate(R.layout.send_coins_fragment, container);

    final MyRemoteWallet wallet = application.getRemoteWallet();

    if (wallet == null)
        return view;

    BigInteger available = null;/*ww  w .  ja  va  2 s.c  o  m*/

    if (application.isInP2PFallbackMode()) {
        try {
            available = application.bitcoinjWallet.getBalance(BalanceType.ESTIMATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        available = wallet.getBalance();
    }

    receivingAddressView = (AutoCompleteTextView) view.findViewById(R.id.send_coins_receiving_address);
    feeContainerView = view.findViewById(R.id.send_coins_fee_container);
    sendCoinsFromContainer = view.findViewById(R.id.send_coins_from_container);
    sendCoinsFromSpinner = (Spinner) view.findViewById(R.id.send_coins_from_spinner);
    feeAmountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_fee);
    sendTypeDescriptionContainer = view.findViewById(R.id.send_type_description_container);
    sendTypeDescription = (TextView) view.findViewById(R.id.send_type_description);
    sendTypeDescriptionIcon = (ImageView) view.findViewById(R.id.send_type_description_icon);

    {
        //Construct the from drop down list
        String[] activeAddresses = wallet.getActiveAddresses();
        Map<String, String> labelMap = wallet.getLabelMap();

        List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();
        for (String address : activeAddresses) {

            String label = labelMap.get(address);

            if (label == null || label.length() == 0) {
                label = "No Label";
            }

            BigInteger balance = wallet.getBalance(address);

            if (balance.compareTo(BigInteger.ZERO) > 0) {
                label += " (" + WalletUtils.formatValue(balance) + " BTC)";

                pairs.add(new Pair<String, String>(address, label));
            }
        }

        pairs.add(0, new Pair<String, String>("Any Address", "Any Address"));

        sendCoinsFromSpinner.setAdapter(new SpinAdapter(activity, android.R.layout.simple_list_item_1, pairs));
    }

    feeAmountView.setAmount(wallet.getBaseFee());

    StringPairAdapter adapter = new StringPairAdapter(this.getLabelList());

    receivingAddressView.setAdapter(adapter);
    receivingAddressView.addTextChangedListener(textWatcher);

    receivingAddressView.setOnTouchListener(new RightDrawableOnTouchListener(receivingAddressView) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            activity.showQRReader(activity.new QrCodeDelagate() {
                @Override
                public void didReadQRCode(String data) {
                    activity.handleScanURI(data);
                }
            });

            return true;
        }
    });

    receivingAddressErrorView = view.findViewById(R.id.send_coins_receiving_address_error);

    availableViewContainer = view.findViewById(R.id.send_coins_available_container);
    availableView = (CurrencyAmountView) view.findViewById(R.id.send_coins_available);
    availableView.setAmount(available);

    amountView = (CurrencyAmountView) view.findViewById(R.id.send_coins_amount);
    amountView.setListener(listener);
    amountView.setContextButton(R.drawable.ic_input_calculator, new OnClickListener() {
        public void onClick(final View v) {
            final FragmentTransaction ft = getFragmentManager().beginTransaction();
            final Fragment prev = getFragmentManager().findFragmentByTag(AmountCalculatorFragment.FRAGMENT_TAG);
            if (prev != null)
                ft.remove(prev);
            ft.addToBackStack(null);
            final DialogFragment newFragment = new AmountCalculatorFragment(
                    new AmountCalculatorFragment.Listener() {
                        public void use(final BigInteger amount) {
                            amountView.setAmount(amount);
                        }
                    });
            newFragment.show(ft, AmountCalculatorFragment.FRAGMENT_TAG);
        }
    });

    viewGo = (Button) view.findViewById(R.id.send_coins_go);
    viewGo.setOnClickListener(new OnClickListener() {
        final SendProgress progress = new SendProgress() {
            public void onSend(final Transaction tx, final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENT;

                        activity.longToast(message);

                        Intent intent = activity.getIntent();
                        intent.putExtra("tx", tx.getHash());
                        activity.setResult(Activity.RESULT_OK, intent);

                        activity.finish();

                        updateView();
                    }
                });

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                application.doMultiAddr(true);
            }

            public void onError(final String message) {
                handler.post(new Runnable() {
                    public void run() {

                        System.out.println("On Error");

                        if (message != null)
                            activity.longToast(message);

                        state = State.INPUT;

                        updateView();
                    }
                });
            }

            public void onProgress(final String message) {
                handler.post(new Runnable() {
                    public void run() {
                        state = State.SENDING;

                        updateView();
                    }
                });
            }

            public boolean onReady(Transaction tx, BigInteger fee, FeePolicy feePolicy, long priority) {

                boolean containsOutputLessThanThreshold = false;
                for (TransactionOutput output : tx.getOutputs()) {
                    if (output.getValue().compareTo(Constants.FEE_THRESHOLD_MIN) < 0) {
                        containsOutputLessThanThreshold = true;
                        break;
                    }
                }

                if (feePolicy != FeePolicy.FeeNever && fee.compareTo(BigInteger.ZERO) == 0) {
                    if (tx.bitcoinSerialize().length > 1024 || containsOutputLessThanThreshold) {
                        makeTransaction(FeePolicy.FeeForce);
                        return false;
                    } else if (priority < 97600000L) {
                        handler.post(new Runnable() {
                            public void run() {
                                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                                builder.setMessage(R.string.ask_for_fee).setCancelable(false);

                                AlertDialog alert = builder.create();

                                alert.setButton(AlertDialog.BUTTON_NEUTRAL,
                                        getString(R.string.continue_without_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeNever);
                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.add_fee),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                makeTransaction(FeePolicy.FeeForce);

                                                dialog.dismiss();
                                            }
                                        });

                                alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                dialog.dismiss();
                                            }
                                        });

                                alert.show();
                            }
                        });

                        handler.post(new Runnable() {
                            public void run() {
                                state = State.INPUT;
                                updateView();
                            }
                        });
                        return false;
                    }
                }

                return true;
            }

            public ECKey onPrivateKeyMissing(final String address) {

                handler.post(new Runnable() {
                    public void run() {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(getString(R.string.ask_for_private_key, address))
                                .setCancelable(false)
                                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        activity.scanPrivateKeyAddress = address;

                                        activity.showQRReader(activity.new QrCodeDelagate() {
                                            @Override
                                            public void didReadQRCode(String data) throws Exception {
                                                activity.handleScanPrivateKey(data);
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                        synchronized (activity.temporaryPrivateKeys) {
                                            activity.temporaryPrivateKeys.notify();
                                        }

                                        dialog.cancel();
                                    }
                                });

                        AlertDialog alert = builder.create();

                        alert.show();
                    }
                });

                try {
                    synchronized (activity.temporaryPrivateKeys) {
                        activity.temporaryPrivateKeys.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return activity.temporaryPrivateKeys.get(address);
            }
        };

        public void send(Address receivingAddress, BigInteger fee, FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            if (sendType != null && !sendType.equals(SendCoinsActivity.SendTypeQuickSend)
                    && application.isInP2PFallbackMode()) {
                activity.longToast(R.string.only_quick_supported);
                return;
            }

            String[] from;
            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                Pair<String, String> selected = (Pair<String, String>) sendCoinsFromSpinner.getSelectedItem();

                if (selected.first.equals("Any Address")) {
                    from = wallet.getActiveAddresses();
                } else {
                    from = new String[] { selected.first.toString() };
                }
            } else {
                from = wallet.getActiveAddresses();
            }

            final BigInteger amount;

            if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {
                BigDecimal amountDecimal = BigDecimal.valueOf(amountView.getAmount().doubleValue());

                //Add the fee
                amount = amountDecimal.add(amountDecimal.divide(BigDecimal.valueOf(100))
                        .multiply(BigDecimal.valueOf(wallet.getSharedFee()))).toBigInteger();
            } else {
                amount = amountView.getAmount();
            }

            final WalletApplication application = (WalletApplication) getActivity().getApplication();

            if (application.isInP2PFallbackMode()) {

                final long blockchainLag = System.currentTimeMillis()
                        - service.blockChain.getChainHead().getHeader().getTime().getTime();

                final boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS;

                if (!blockchainUptodate) {
                    activity.longToast(R.string.blockchain_not_upto_date);
                    return;
                }

                // create spend
                final SendRequest sendRequest = SendRequest.to(receivingAddress, amountView.getAmount());

                sendRequest.fee = fee;

                new Thread(new Runnable() {
                    public void run() {
                        final Transaction transaction = application.bitcoinjWallet
                                .sendCoinsOffline(sendRequest);

                        handler.post(new Runnable() {
                            public void run() {
                                if (transaction != null) {
                                    state = State.SENDING;

                                    updateView();

                                    service.broadcastTransaction(transaction);

                                    state = State.SENT;

                                    activity.longToast(R.string.wallet_transactions_fragment_tab_sent);

                                    Intent intent = activity.getIntent();
                                    intent.putExtra("tx", transaction.getHash());
                                    activity.setResult(Activity.RESULT_OK, intent);

                                    activity.finish();

                                    updateView();

                                    EventListeners.invokeOnTransactionsChanged();
                                } else {
                                    state = State.INPUT;

                                    updateView();

                                    activity.longToast(R.string.send_coins_error_msg);
                                }
                            }
                        });
                    }
                }).start();
            } else {
                application.getRemoteWallet().sendCoinsAsync(from, receivingAddress.toString(), amount,
                        feePolicy, fee, progress);
            }
        }

        public void makeTransaction(FeePolicy feePolicy) {

            if (application.getRemoteWallet() == null)
                return;

            try {
                MyRemoteWallet wallet = application.getRemoteWallet();

                BigInteger baseFee = wallet.getBaseFee();

                BigInteger fee = null;

                if (feePolicy == FeePolicy.FeeForce) {
                    fee = baseFee;
                } else if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeCustomSend)) {
                    feePolicy = FeePolicy.FeeOnlyIfNeeded;
                    fee = feeAmountView.getAmount();
                } else {
                    fee = (wallet.getFeePolicy() == 1) ? baseFee : BigInteger.ZERO;
                }

                final BigInteger finalFee = fee;
                final FeePolicy finalFeePolicy = feePolicy;

                if (sendType != null && sendType.equals(SendCoinsActivity.SendTypeSharedSend)) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                final String addressString = MyRemoteWallet
                                        .generateSharedAddress(getToAddress());

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            send(new Address(Constants.NETWORK_PARAMETERS, addressString),
                                                    finalFee, finalFeePolicy);
                                        } catch (Exception e) {
                                            e.printStackTrace();

                                            Toast.makeText(application, e.getLocalizedMessage(),
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            } catch (final Exception e) {
                                handler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        e.printStackTrace();

                                        Toast.makeText(application, e.getLocalizedMessage(), Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            }
                        }

                    }).start();

                } else {
                    String addressString = getToAddress();

                    Address receivingAddress = new Address(Constants.NETWORK_PARAMETERS, addressString);

                    send(receivingAddress, fee, feePolicy);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onClick(final View v) {
            if (application.getRemoteWallet() == null)
                return;

            MyRemoteWallet remoteWallet = application.getRemoteWallet();

            if (remoteWallet.isDoubleEncrypted() == false) {
                makeTransaction(FeePolicy.FeeOnlyIfNeeded);
            } else {
                if (remoteWallet.temporySecondPassword == null) {
                    RequestPasswordDialog.show(getFragmentManager(), new SuccessCallback() {

                        public void onSuccess() {
                            makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                        }

                        public void onFail() {
                            Toast.makeText(application, R.string.send_no_password_error, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }, RequestPasswordDialog.PasswordTypeSecond);
                } else {
                    makeTransaction(FeePolicy.FeeOnlyIfNeeded);
                }
            }
        }
    });

    viewCancel = (Button) view.findViewById(R.id.send_coins_cancel);
    viewCancel.setOnClickListener(new OnClickListener() {
        public void onClick(final View v) {
            activity.setResult(Activity.RESULT_CANCELED);

            activity.finish();
        }
    });

    activity.setOnChangedSendTypeListener(new OnChangedSendTypeListener() {
        @Override
        public void onChangedSendType(String type) {
            sendType = type;

            feeContainerView.setVisibility(View.GONE);
            sendCoinsFromContainer.setVisibility(View.GONE);
            availableViewContainer.setVisibility(View.VISIBLE);
            sendTypeDescriptionContainer.setVisibility(View.GONE);

            if (type.equals(SendCoinsActivity.SendTypeCustomSend)) {
                feeContainerView.setVisibility(View.VISIBLE);
                sendCoinsFromContainer.setVisibility(View.VISIBLE);
                availableViewContainer.setVisibility(View.GONE);
            } else if (type.equals(SendCoinsActivity.SendTypeSharedSend)) {
                sendTypeDescriptionContainer.setVisibility(View.VISIBLE);
                sendTypeDescription
                        .setText(getString(R.string.shared_send_description, wallet.getSharedFee() + "%"));
                sendTypeDescriptionIcon.setImageResource(R.drawable.ic_icon_shared);
            }
        }
    });

    updateView();

    return view;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic sine./*from w w w .j  av a  2 s  .  c  o  m*/
 *
 * @param x the argument.
 * @return the sinh(x) = (exp(x)-exp(-x))/2 .
 */
static public BigDecimal sinh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sinh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        if (x.doubleValue() > 2.4) {
            /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
             */
            BigDecimal two = new BigDecimal(2);
            BigDecimal xhalf = x.divide(two);

            BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two);
            /* The error in the result is set by the error in x itself.
             * The first derivative of sinh(x) is cosh(x), so the absolute error
             * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
             */

            double eps = Math.tanh(x.doubleValue());
            MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps));

            return resul.round(mc);

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */
            BigDecimal resul = xhighpr;
            /* x^i */
            BigDecimal xpowi = xhighpr;
            /* 2i+1 factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The error in the result is set by the error in x itself.
             */

            double xUlpDbl = x.ulp().doubleValue();
            /* The error in the result is set by the error in x itself.
             * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
             * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
             * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
             */

            int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2;
            MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i or 2*i+1 overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is set by the error in x itself.
              */
            MathContext mc = new MathContext(x.precision());

            return resul.round(mc);

        }
    }
}

From source file:org.egov.works.web.actions.estimate.EstimatePDFGenerator.java

private PdfPTable createBudgetDetailsForEstimateTable(final AbstractEstimate estimate)
        throws DocumentException {
    try {/*from   www  .ja  v  a 2 s.  c  o  m*/

        final PdfPTable estBudgetDetailsTable = new PdfPTable(4);
        estBudgetDetailsTable.setWidthPercentage(75);
        estBudgetDetailsTable.setWidths(new float[] { 0.6f, 1f, 0.5f, 1f });

        BigDecimal totalGrant;
        BigDecimal budgetAvailable;
        BigDecimal balOnHand;
        BigDecimal amtAppropriated = BigDecimal.ZERO;
        BigDecimal totGrantafterMultiFactor = BigDecimal.ZERO;

        BigDecimal totalUtilizedAmt;
        BigDecimal amtAppropriatedsofar = BigDecimal.ZERO;
        worksService.getAccountdetailtypeByName("DEPOSITCODE");
        AbstractEstimateAppropriation latestAbstractEstimateAppropriation;

        if (abstractEstimateAppropriationList != null && !abstractEstimateAppropriationList.isEmpty()) {
            latestAbstractEstimateAppropriation = abstractEstimateAppropriationList
                    .get(abstractEstimateAppropriationList.size() - 1);

            if (latestAbstractEstimateAppropriation != null)
                if (estimate.getDepositCode() == null) {
                    if (latestAbstractEstimateAppropriation.getBudgetUsage().getConsumedAmount() != 0) {
                        final Department dept = getDeptFromBudgtAppropriationNo(
                                latestAbstractEstimateAppropriation.getBudgetUsage().getAppropriationnumber());
                        totalGrant = abstractEstimateService.getTotalGrantForYearAsOnDate(
                                estimate.getFinancialDetails().get(0),
                                latestAbstractEstimateAppropriation.getBudgetUsage().getFinancialYearId()
                                        .longValue(),
                                Integer.parseInt(dept.getId().toString()),
                                latestAbstractEstimateAppropriation.getBudgetUsage().getUpdatedTime());
                        final BigDecimal planningBudgetPerc = abstractEstimateService
                                .getPlanningBudgetPercentage(estimate.getFinancialDetails().get(0),
                                        latestAbstractEstimateAppropriation.getBudgetUsage()
                                                .getFinancialYearId().longValue(),
                                        Integer.parseInt(dept.getId().toString()));
                        if (planningBudgetPerc != null && planningBudgetPerc.compareTo(BigDecimal.ZERO) != 0) {
                            totGrantafterMultiFactor = totalGrant
                                    .multiply(planningBudgetPerc.divide(new BigDecimal(100)));
                            appValue = planningBudgetPerc.divide(new BigDecimal(100)).toString();
                        }

                        budgetAvailable = latestAbstractEstimateAppropriation.getBalanceAvailable();
                        balOnHand = budgetAvailable.add(new BigDecimal(
                                latestAbstractEstimateAppropriation.getBudgetUsage().getConsumedAmount()));
                        amtAppropriated = totGrantafterMultiFactor.subtract(balOnHand);
                    }
                } else if (latestAbstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount()
                        .doubleValue() != 0) {
                    totalUtilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks(
                            latestAbstractEstimateAppropriation.getAbstractEstimate().getFinancialDetails()
                                    .get(0),
                            latestAbstractEstimateAppropriation.getDepositWorksUsage().getCreatedDate());
                    if (totalUtilizedAmt == null)
                        totalUtilizedAmt = BigDecimal.ZERO;
                    amtAppropriatedsofar = totalUtilizedAmt.subtract(
                            latestAbstractEstimateAppropriation.getDepositWorksUsage().getConsumedAmount());
                }
        }
        addRow(estBudgetDetailsTable, true, centerPara("Estimate Date"),
                centerPara(DateUtils.getFormattedDate(estimate.getEstimateDate(), "dd/MM/yyyy")),
                centerPara("Fund"), centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                        : estimate.getFinancialDetails().get(0).getFund().getName()));
        if (estimate.getDepositCode() == null) {
            addRow(estBudgetDetailsTable, true, centerPara("Function "),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getFunction().getName()),
                    centerPara("Budget Head"), centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getBudgetGroup().getName()));
            addRow(estBudgetDetailsTable, true, centerPara("Amount Appropriated so far"),
                    centerPara(amtAppropriated == null ? "" : toCurrency(amtAppropriated.doubleValue())),
                    centerPara("Estimate Amount"),
                    centerPara(toCurrency(estimate.getTotalAmount().getValue())));
        } else {
            addRow(estBudgetDetailsTable, true, centerPara("Function "),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getFunction().getName()),
                    centerPara("Deposit COA/Deposit Code"),
                    centerPara(estimate.getFinancialDetails().isEmpty() ? ""
                            : estimate.getFinancialDetails().get(0).getCoa().getGlcode().concat("-")
                                    .concat(estimate.getFinancialDetails().get(0).getCoa().getName())
                                    .concat(" / ").concat(estimate.getDepositCode().getCode())));
            addRow(estBudgetDetailsTable, true, centerPara("Amount Appropriated so far"),
                    centerPara(
                            amtAppropriatedsofar == null ? "" : toCurrency(amtAppropriatedsofar.doubleValue())),
                    centerPara("Estimate Amount"),
                    makePara(toCurrency(estimate.getTotalAmount().getValue()), Element.ALIGN_RIGHT));
        }

        return estBudgetDetailsTable;
    } catch (final Exception e) {
        throw new ApplicationRuntimeException("Exception occured while estimate details method 2 " + e);
    }
}

From source file:org.kuali.kfs.gl.batch.service.impl.PosterServiceImpl.java

/**
 * Generate a transfer transaction and an offset transaction
 *
 * @param et an expenditure transaction/* www .j  a  v a  2 s.  c  o  m*/
 * @param icrEntry the indirect cost recovery entry
 * @param generatedTransactionAmount the amount of the transaction
 * @param runDate the transaction date for the newly created origin entry
 * @param group the group to save the origin entry to
 */
protected void generateTransactions(ExpenditureTransaction et, IndirectCostRecoveryRateDetail icrRateDetail,
        KualiDecimal generatedTransactionAmount, Date runDate, PrintStream group,
        IndirectCostRecoveryGenerationMetadata icrGenerationMetadata) {

    BigDecimal pct = new BigDecimal(icrRateDetail.getAwardIndrCostRcvyRatePct().toString());
    pct = pct.divide(BDONEHUNDRED);

    OriginEntryFull e = new OriginEntryFull();
    e.setTransactionLedgerEntrySequenceNumber(0);

    // SYMBOL_USE_EXPENDITURE_ENTRY means we use the field from the expenditure entry, SYMBOL_USE_IRC_FROM_ACCOUNT
    // means we use the ICR field from the account record, otherwise, use the field in the icrRateDetail
    if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY
            .equals(icrRateDetail.getFinancialObjectCode())
            || GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT
                    .equals(icrRateDetail.getFinancialObjectCode())) {
        e.setFinancialObjectCode(et.getObjectCode());
        e.setFinancialSubObjectCode(et.getSubObjectCode());
    } else {
        e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode());
        e.setFinancialSubObjectCode(icrRateDetail.getFinancialSubObjectCode());
    }

    if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY
            .equals(icrRateDetail.getAccountNumber())) {
        e.setAccountNumber(et.getAccountNumber());
        e.setChartOfAccountsCode(et.getChartOfAccountsCode());
        e.setSubAccountNumber(et.getSubAccountNumber());
    } else if (GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT
            .equals(icrRateDetail.getAccountNumber())) {
        e.setAccountNumber(icrGenerationMetadata.getIndirectCostRecoveryAcctNbr());
        e.setChartOfAccountsCode(icrGenerationMetadata.getIndirectCostRcvyFinCoaCode());
        e.setSubAccountNumber(KFSConstants.getDashSubAccountNumber());
    } else {
        e.setAccountNumber(icrRateDetail.getAccountNumber());
        e.setSubAccountNumber(icrRateDetail.getSubAccountNumber());
        e.setChartOfAccountsCode(icrRateDetail.getChartOfAccountsCode());
        // TODO Reporting thing line 1946
    }
    // take care of infinite recursive error case - do not generate entries
    if ((et.getAccountNumber().equals(e.getAccountNumber()))
            && (et.getChartOfAccountsCode().equals(e.getChartOfAccountsCode()))
            && (et.getSubAccountNumber().equals(e.getSubAccountNumber()))
            && (et.getObjectCode().equals(e.getFinancialObjectCode()))
            && (et.getSubObjectCode().equals(e.getFinancialSubObjectCode()))) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(new Message("Infinite recursive encumbrance error " + et.getChartOfAccountsCode() + " "
                + et.getAccountNumber() + " " + et.getSubAccountNumber() + " " + et.getObjectCode() + " "
                + et.getSubObjectCode(), Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);
        return;
    }

    e.setFinancialDocumentTypeCode(
            parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class,
                    KFSConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY));
    e.setFinancialSystemOriginationCode(
            parameterService.getParameterValueAsString(KfsParameterConstants.GENERAL_LEDGER_BATCH.class,
                    KFSConstants.SystemGroupParameterNames.GL_ORIGINATION_CODE));
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STRING);
    e.setDocumentNumber(sdf.format(runDate));
    if (KFSConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
        e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(),
                icrGenerationMetadata.getIndirectCostRecoveryTypeCode(),
                et.getAccountObjectDirectCostAmount().abs()));
    } else {
        e.setTransactionLedgerEntryDescription(
                getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(),
                        et.getChartOfAccountsCode(), et.getAccountNumber()));
    }
    e.setTransactionDate(new java.sql.Date(runDate.getTime()));
    e.setTransactionDebitCreditCode(icrRateDetail.getTransactionDebitIndicator());
    e.setFinancialBalanceTypeCode(et.getBalanceTypeCode());
    e.setUniversityFiscalYear(et.getUniversityFiscalYear());
    e.setUniversityFiscalPeriodCode(et.getUniversityFiscalAccountingPeriod());

    ObjectCode oc = objectCodeService.getByPrimaryId(e.getUniversityFiscalYear(), e.getChartOfAccountsCode(),
            e.getFinancialObjectCode());
    if (oc == null) {
        LOG.warn(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND_FOR)
                + e.getUniversityFiscalYear() + "," + e.getChartOfAccountsCode() + ","
                + e.getFinancialObjectCode());
        e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode()); // this will be written out the ICR file. Then, when that file attempts to post, the transaction won't validate and will end up in the icr error file
    } else {
        e.setFinancialObjectTypeCode(oc.getFinancialObjectTypeCode());
    }

    if (generatedTransactionAmount.isNegative()) {
        if (KFSConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
            e.setTransactionDebitCreditCode(KFSConstants.GL_CREDIT_CODE);
        } else {
            e.setTransactionDebitCreditCode(KFSConstants.GL_DEBIT_CODE);
        }
        e.setTransactionLedgerEntryAmount(generatedTransactionAmount.negated());
    } else {
        e.setTransactionLedgerEntryAmount(generatedTransactionAmount);
    }

    if (et.getBalanceTypeCode().equals(et.getOption().getExtrnlEncumFinBalanceTypCd())
            || et.getBalanceTypeCode().equals(et.getOption().getIntrnlEncumFinBalanceTypCd())
            || et.getBalanceTypeCode().equals(et.getOption().getPreencumbranceFinBalTypeCd())
            || et.getBalanceTypeCode().equals(et.getOption().getCostShareEncumbranceBalanceTypeCd())) {
        e.setDocumentNumber(
                parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class,
                        KFSConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY));
    }
    e.setProjectCode(et.getProjectCode());
    if (GeneralLedgerConstants.getDashOrganizationReferenceId().equals(et.getOrganizationReferenceId())) {
        e.setOrganizationReferenceId(null);
    } else {
        e.setOrganizationReferenceId(et.getOrganizationReferenceId());
    }
    // TODO 2031-2039
    try {
        createOutputEntry(e, group);
    } catch (IOException ioe) {
        LOG.error("generateTransactions Stopped: " + ioe.getMessage());
        throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe);
    }

    // Now generate Offset
    e = new OriginEntryFull(e);
    if (KFSConstants.GL_DEBIT_CODE.equals(e.getTransactionDebitCreditCode())) {
        e.setTransactionDebitCreditCode(KFSConstants.GL_CREDIT_CODE);
    } else {
        e.setTransactionDebitCreditCode(KFSConstants.GL_DEBIT_CODE);
    }
    e.setFinancialSubObjectCode(KFSConstants.getDashFinancialSubObjectCode());

    String offsetBalanceSheetObjectCodeNumber = determineIcrOffsetBalanceSheetObjectCodeNumber(e, et,
            icrRateDetail);
    e.setFinancialObjectCode(offsetBalanceSheetObjectCodeNumber);
    ObjectCode balSheetObjectCode = objectCodeService.getByPrimaryId(icrRateDetail.getUniversityFiscalYear(),
            e.getChartOfAccountsCode(), offsetBalanceSheetObjectCodeNumber);
    if (balSheetObjectCode == null) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(new Message(
                configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_INVALID_OFFSET_OBJECT_CODE)
                        + icrRateDetail.getUniversityFiscalYear() + "-" + e.getChartOfAccountsCode() + "-"
                        + offsetBalanceSheetObjectCodeNumber,
                Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);

    } else {
        e.setFinancialObjectTypeCode(balSheetObjectCode.getFinancialObjectTypeCode());
    }

    if (KFSConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) {
        e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(),
                icrGenerationMetadata.getIndirectCostRecoveryTypeCode(),
                et.getAccountObjectDirectCostAmount().abs()));
    } else {
        e.setTransactionLedgerEntryDescription(
                getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(),
                        et.getChartOfAccountsCode(), et.getAccountNumber()));
    }

    try {
        flexibleOffsetAccountService.updateOffset(e);
    } catch (InvalidFlexibleOffsetException ex) {
        List<Message> warnings = new ArrayList<Message>();
        warnings.add(
                new Message("FAILED TO GENERATE FLEXIBLE OFFSETS " + ex.getMessage(), Message.TYPE_WARNING));
        reportWriterService.writeError(et, warnings);
        LOG.warn("FAILED TO GENERATE FLEXIBLE OFFSETS FOR EXPENDITURE TRANSACTION " + et.toString(), ex);
    }

    try {
        createOutputEntry(e, group);
    } catch (IOException ioe) {
        LOG.error("generateTransactions Stopped: " + ioe.getMessage());
        throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe);
    }
}

From source file:com.mg.merp.planning.support.MPSProcessorServiceBean.java

private void calculateDependantDemand(short lowLevelCode) {
    for (MpsLine mpsLine : new ArrayList<MpsLine>(generatedMPSLines)) { // ? , ..  ? ? ?? generatedMPSLines
        if (mpsLine.getLevelCode() == lowLevelCode && MathUtils.compareToZero(mpsLine.getPlannedQty()) > 0) {
            BucketRange bucketRange = MfUtils.determineBucketRange(mps.getPlanningLevel().getId(),
                    mpsLine.getBucketOffset());
            BigDecimal PlannedQty = mpsLine.getPlannedQty(), MaxLotQty, Remainder, OddJobSize;
            PlannedQty = getMeasureConversionService().conversion(mpsLine.getMeasure(),
                    mpsLine.getPlanningItem().getCatalog().getMeasure1(),
                    mpsLine.getPlanningItem().getCatalog(), bucketRange.getBucketStart(), PlannedQty);

            Bom bom = bomService.findCurrentBOM(mpsLine.getPlanningItem().getCatalog().getId());
            if (bom == null)
                continue;

            MaxLotQty = bom.getMaxLotQty();
            if (MathUtils.compareToZero(MaxLotQty) == 0)
                MaxLotQty = PlannedQty; //Infinite maximum size
            long NumberOfMaxJobs = PlannedQty.divide(MaxLotQty).longValue();
            Remainder = PlannedQty.subtract(MaxLotQty.multiply(new BigDecimal(NumberOfMaxJobs)));
            OddJobSize = Remainder;/*from   w  w w  .  j  ava2  s  . c  o m*/

            long CurrentRequiredDate = MfUtils.dateToTick(DateTimeUtils.incDay(bucketRange.getBucketEnd(), 1))
                    - 1000; //   ?
            mpsMaterialBreakdown(bom, mpsLine, 1,
                    MaxLotQty.multiply(new BigDecimal(NumberOfMaxJobs)).add(OddJobSize), CurrentRequiredDate);
        }
    }
}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
 * @throws Exception/*from w  w w.ja  v a 2  s .  c  o  m*/
 * 
 */
public CartViewBean buildCartViewBean(final RequestData requestData, final Cart cart) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();

    final CartViewBean cartViewBean = new CartViewBean();

    cartViewBean.setCartDetailsUrl(urlService.generateUrl(FoUrls.CART_DETAILS, requestData));
    cartViewBean.setCartAuthUrl(urlService.generateUrl(FoUrls.CART_AUTH, requestData));
    cartViewBean.setCartDeliveryAndOrderDetailsUrl(urlService.generateUrl(FoUrls.CART_DELIVERY, requestData));
    cartViewBean.setCartOrderPaymentUrl(urlService.generateUrl(FoUrls.CART_ORDER_PAYMENT, requestData));
    cartViewBean
            .setCartOrderConfirmationUrl(urlService.generateUrl(FoUrls.CART_ORDER_CONFIRMATION, requestData));

    cartViewBean.setAddNewAddressUrl(urlService.generateUrl(FoUrls.PERSONAL_ADD_ADDRESS, requestData));

    // ITEMS PART
    List<CartItemViewBean> cartItemViewBeans = new ArrayList<CartItemViewBean>();
    Set<CartItem> cartItems = cart.getCartItems();
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        cartItemViewBeans.add(buildCartItemViewBean(requestData, cartItem));
    }
    cartViewBean.setCartItems(cartItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal cartItemsTotal = new BigDecimal("0");
    BigDecimal cartShippingTotal = new BigDecimal("0");
    BigDecimal cartFeesTotal = new BigDecimal("0");
    BigDecimal carTotal = new BigDecimal("0");
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        if (cartItem.getPrice() != null) {
            cartItemsTotal = cartItemsTotal.add(cartItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<CartShippingViewBean> cartShippingViewBeans = new ArrayList<CartShippingViewBean>();
    final Set<Shipping> shippings = cart.getShippings();
    if (shippings != null) {
        for (Iterator<Shipping> iterator = shippings.iterator(); iterator.hasNext();) {
            final Shipping shipping = (Shipping) iterator.next();
            final CartShippingViewBean cartShippingViewBean = new CartShippingViewBean();
            if (shipping.getPrice() != null) {
                cartShippingTotal = cartShippingTotal.add(shipping.getPrice());
                cartShippingViewBean.setCartShippingTotal(formatter.format(shipping.getPrice()));
            }
            Object[] params = { shipping.getName() };
            cartShippingViewBean.setCartShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            cartShippingViewBeans.add(cartShippingViewBean);
        }
        cartViewBean.setCartShippings(cartShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<CartTaxViewBean> cartTaxViewBeans = new ArrayList<CartTaxViewBean>();
    final Set<Tax> taxes = cart.getTaxes();
    if (taxes != null) {
        for (Iterator<Tax> iterator = taxes.iterator(); iterator.hasNext();) {
            final Tax tax = (Tax) iterator.next();
            final CartTaxViewBean cartTaxViewBean = new CartTaxViewBean();
            BigDecimal taxesCalc = cartItemsTotal;
            taxesCalc = taxesCalc.multiply(tax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            cartFeesTotal = cartFeesTotal.add(taxesCalc);
            Object[] params = { tax.getName() };
            cartTaxViewBean.setCartTaxTotal(formatter.format(taxesCalc));
            cartTaxViewBean.setCartTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            cartTaxViewBeans.add(cartTaxViewBean);
        }
        cartViewBean.setCartTaxes(cartTaxViewBeans);
    }
    carTotal = carTotal.add(cartItemsTotal);
    carTotal = carTotal.add(cartShippingTotal);
    carTotal = carTotal.add(cartFeesTotal);
    cartViewBean.setCartItemsTotal(formatter.format(cartItemsTotal));
    cartViewBean.setCartShippingTotal(formatter.format(cartShippingTotal));
    cartViewBean.setCartFeesTotal(formatter.format(cartFeesTotal));
    cartViewBean.setCartTotal(formatter.format(carTotal));

    return cartViewBean;
}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
  * /*  ww  w .  ja v a2s . co  m*/
  */
public OrderViewBean buildOrderViewBean(final RequestData requestData, final Order order) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    final String orderId = order.getId().toString();
    final OrderViewBean orderViewBean = new OrderViewBean();

    // ITEMS PART
    final List<OrderItemViewBean> orderItemViewBeans = new ArrayList<OrderItemViewBean>();
    final Set<OrderItem> orderItems = order.getOrderItems();
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        OrderItem orderItem = (OrderItem) iterator.next();
        orderItemViewBeans.add(buildOrderItemViewBean(requestData, orderItem));
    }
    orderViewBean.setOrderItems(orderItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal orderItemsTotal = new BigDecimal("0");
    BigDecimal orderShippingTotal = new BigDecimal("0");
    BigDecimal orderFeesTotal = new BigDecimal("0");
    BigDecimal orderTotal = new BigDecimal("0");
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        final OrderItem orderItem = (OrderItem) iterator.next();
        if (orderItem.getPrice() != null) {
            orderItemsTotal = orderItemsTotal.add(orderItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<OrderShippingViewBean> orderShippingViewBeans = new ArrayList<OrderShippingViewBean>();
    final Set<OrderShipment> orderShipments = order.getOrderShipments();
    if (orderShipments != null) {
        for (Iterator<OrderShipment> iterator = orderShipments.iterator(); iterator.hasNext();) {
            final OrderShipment orderShipment = (OrderShipment) iterator.next();
            final OrderShippingViewBean orderShippingViewBean = new OrderShippingViewBean();
            if (orderShipment.getPrice() != null) {
                orderShippingTotal = orderShippingTotal.add(orderShipment.getPrice());
                orderShippingViewBean.setOrderShippingTotal(formatter.format(orderShipment.getPrice()));
            }
            Object[] params = { orderShipment.getName() };
            orderShippingViewBean.setOrderShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            orderShippingViewBeans.add(orderShippingViewBean);
        }
        orderViewBean.setOrderShippings(orderShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<OrderTaxViewBean> orderTaxViewBeans = new ArrayList<OrderTaxViewBean>();
    final Set<OrderTax> orderTaxes = order.getOrderTaxes();
    if (orderTaxes != null) {
        for (Iterator<OrderTax> iterator = orderTaxes.iterator(); iterator.hasNext();) {
            final OrderTax orderTax = (OrderTax) iterator.next();
            final OrderTaxViewBean orderTaxViewBean = new OrderTaxViewBean();
            BigDecimal taxesCalc = orderItemsTotal;
            taxesCalc = taxesCalc.multiply(orderTax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            orderFeesTotal = orderFeesTotal.add(taxesCalc);
            Object[] params = { orderTax.getName() };
            orderTaxViewBean.setOrderTaxTotal(formatter.format(taxesCalc));
            orderTaxViewBean.setOrderTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            orderTaxViewBeans.add(orderTaxViewBean);
        }
        orderViewBean.setOrderTaxes(orderTaxViewBeans);
    }
    orderTotal = orderTotal.add(orderItemsTotal);
    orderTotal = orderTotal.add(orderShippingTotal);
    orderTotal = orderTotal.add(orderFeesTotal);
    orderViewBean.setOrderItemsTotal(formatter.format(orderItemsTotal));
    orderViewBean.setOrderShippingTotal(formatter.format(orderShippingTotal));
    orderViewBean.setOrderFeesTotal(formatter.format(orderFeesTotal));
    orderViewBean.setOrderTotal(formatter.format(orderTotal));

    // final Object[] params = {order.getOrderNum()};
    // orderViewBean.setConfirmationMessage(getSpecificMessage(ScopeWebMessage.COMMON,
    // "order.confirmation.message", params, locale));

    Map<String, String> urlParams = new HashMap<String, String>();
    urlParams.put(RequestConstants.REQUEST_PARAMETER_CUSTOMER_ORDER_ID, orderId.toString());

    orderViewBean
            .setOrderDetailsUrl(urlService.generateUrl(FoUrls.PERSONAL_ORDER_DETAILS, requestData, urlParams));

    return orderViewBean;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Trigonometric sine.// w ww .  j a  v  a 2 s  . c  o m
 *
 * @param x The argument in radians.
 * @return sin(x) in the range -1 to 1.
 */
static public BigDecimal sin(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sin(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* reduce modulo 2pi
         */
        BigDecimal res = mod2pi(x);
        double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
        int val = 2 + err2prec(FastMath.PI, errpi);
        MathContext mc = new MathContext(val);
        BigDecimal p = pi(mc);
        mc = new MathContext(x.precision());
        if (res.compareTo(p) > 0) {
            /* pi<x<=2pi: sin(x)= - sin(x-pi)
             */
            return sin(subtractRound(res, p)).negate();
        } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) {
            /* pi/2<x<=pi: sin(x)= sin(pi-x)
             */
            return sin(subtractRound(p, res));
        } else {
            /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x)
             * to split this further. Here, use the sine up to pi/4 and the cosine higher up.
             */
            if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) {
                /* x>pi/4: sin(x) = cos(pi/2-x)
                 */
                return cos(subtractRound(p.divide(new BigDecimal("2")), res));
            } else {
                /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */
                BigDecimal resul = res;
                /* x^i */
                BigDecimal xpowi = res;
                /* 2i+1 factorial */
                BigInteger ifac = BigInteger.ONE;
                /* The error in the result is set by the error in x itself.
                 */
                double xUlpDbl = res.ulp().doubleValue();
                /* The error in the result is set by the error in x itself.
                 * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
                 * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
                 * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
                 */
                int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2;
                MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k));
                for (int i = 1;; i++) {
                    /* TBD: at which precision will 2*i or 2*i+1 overflow?
                     */
                    ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                    ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                    xpowi = xpowi.multiply(res).multiply(res).negate();
                    BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                    resul = resul.add(corr);
                    if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                        break;
                    }
                }
                /* The error in the result is set by the error in x itself.
                 */
                mc = new MathContext(res.precision());
                return resul.round(mc);
            }
        }
    } /* sin */
}