Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

In this page you can find the example usage for java.text NumberFormat setMaximumFractionDigits.

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:com.crearo.gpslogger.ui.fragments.display.GpsDetailedViewFragment.java

public void displayLocationInfo(Location locationInfo) {
    if (locationInfo == null) {
        return;/*from  w  ww  .  j  a va2  s  .  c  om*/
    }

    showPreferencesAndMessages();

    TextView tvLatitude = (TextView) rootView.findViewById(R.id.detailedview_lat_text);
    TextView tvLongitude = (TextView) rootView.findViewById(R.id.detailedview_lon_text);
    TextView tvDateTime = (TextView) rootView.findViewById(R.id.detailedview_datetime_text);

    TextView tvAltitude = (TextView) rootView.findViewById(R.id.detailedview_altitude_text);

    TextView txtSpeed = (TextView) rootView.findViewById(R.id.detailedview_speed_text);

    TextView txtSatellites = (TextView) rootView.findViewById(R.id.detailedview_satellites_text);
    TextView txtDirection = (TextView) rootView.findViewById(R.id.detailedview_direction_text);
    TextView txtAccuracy = (TextView) rootView.findViewById(R.id.detailedview_accuracy_text);
    TextView txtTravelled = (TextView) rootView.findViewById(R.id.detailedview_travelled_text);
    TextView txtTime = (TextView) rootView.findViewById(R.id.detailedview_duration_text);
    String providerName = locationInfo.getProvider();
    if (providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
        providerName = getString(R.string.providername_gps);
    } else {
        providerName = getString(R.string.providername_celltower);
    }

    tvDateTime.setText(android.text.format.DateFormat.getDateFormat(getActivity())
            .format(new Date(Session.getLatestTimeStamp())) + " - " + providerName);

    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(6);
    tvLatitude.setText(String.valueOf(nf.format(locationInfo.getLatitude())));
    tvLongitude.setText(String.valueOf(nf.format(locationInfo.getLongitude())));

    nf.setMaximumFractionDigits(3);

    if (locationInfo.hasAltitude()) {
        tvAltitude.setText(Strings.getDistanceDisplay(getActivity(), locationInfo.getAltitude(),
                preferenceHelper.shouldDisplayImperialUnits()));
    } else {
        tvAltitude.setText(R.string.not_applicable);
    }

    if (locationInfo.hasSpeed()) {
        txtSpeed.setText(Strings.getSpeedDisplay(getActivity(), locationInfo.getSpeed(),
                preferenceHelper.shouldDisplayImperialUnits()));

    } else {
        txtSpeed.setText(R.string.not_applicable);
    }

    if (locationInfo.hasBearing()) {

        float bearingDegrees = locationInfo.getBearing();
        String direction;

        direction = Strings.getBearingDescription(bearingDegrees, getActivity().getApplicationContext());

        txtDirection.setText(direction + "(" + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol) + ")");
    } else {
        txtDirection.setText(R.string.not_applicable);
    }

    if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
    }

    if (locationInfo.hasAccuracy()) {

        float accuracy = locationInfo.getAccuracy();
        txtAccuracy.setText(getString(R.string.accuracy_within, Strings.getDistanceDisplay(getActivity(),
                accuracy, preferenceHelper.shouldDisplayImperialUnits()), ""));

    } else {
        txtAccuracy.setText(R.string.not_applicable);
    }

    double distanceValue = Session.getTotalTravelled();
    txtTravelled.setText(Strings.getDistanceDisplay(getActivity(), distanceValue,
            preferenceHelper.shouldDisplayImperialUnits()) + " (" + Session.getNumLegs() + " points)");

    long startTime = Session.getStartTimeStamp();
    Date d = new Date(startTime);
    long currentTime = System.currentTimeMillis();

    String duration = Strings.getDescriptiveDurationString((int) (currentTime - startTime) / 1000,
            getActivity());

    DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
    DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
    txtTime.setText(duration + " (started at " + dateFormat.format(d) + " " + timeFormat.format(d) + ")");

}

From source file:com.mendhak.gpslogger.ui.fragments.display.GpsDetailedViewFragment.java

public void displayLocationInfo(Location locationInfo) {
    if (locationInfo == null) {
        return;/*from w  w  w .  j a v  a  2 s .c  o  m*/
    }

    showPreferencesAndMessages();

    TextView tvLatitude = (TextView) rootView.findViewById(R.id.detailedview_lat_text);
    TextView tvLongitude = (TextView) rootView.findViewById(R.id.detailedview_lon_text);
    TextView tvDateTime = (TextView) rootView.findViewById(R.id.detailedview_datetime_text);

    TextView tvAltitude = (TextView) rootView.findViewById(R.id.detailedview_altitude_text);

    TextView txtSpeed = (TextView) rootView.findViewById(R.id.detailedview_speed_text);

    TextView txtSatellites = (TextView) rootView.findViewById(R.id.detailedview_satellites_text);
    TextView txtDirection = (TextView) rootView.findViewById(R.id.detailedview_direction_text);
    TextView txtAccuracy = (TextView) rootView.findViewById(R.id.detailedview_accuracy_text);
    TextView txtTravelled = (TextView) rootView.findViewById(R.id.detailedview_travelled_text);
    TextView txtTime = (TextView) rootView.findViewById(R.id.detailedview_duration_text);
    String providerName = locationInfo.getProvider();
    if (providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
        providerName = getString(R.string.providername_gps);
    } else {
        providerName = getString(R.string.providername_celltower);
    }

    tvDateTime.setText(android.text.format.DateFormat.getDateFormat(getActivity())
            .format(new Date(Session.getLatestTimeStamp())) + " "
            + new SimpleDateFormat("HH:mm:ss").format(new Date(Session.getLatestTimeStamp())) + " - "
            + providerName);

    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(6);
    tvLatitude.setText(String.valueOf(nf.format(locationInfo.getLatitude())));
    tvLongitude.setText(String.valueOf(nf.format(locationInfo.getLongitude())));

    nf.setMaximumFractionDigits(3);

    if (locationInfo.hasAltitude()) {
        tvAltitude.setText(Strings.getDistanceDisplay(getActivity(), locationInfo.getAltitude(),
                preferenceHelper.shouldDisplayImperialUnits()));
    } else {
        tvAltitude.setText(R.string.not_applicable);
    }

    if (locationInfo.hasSpeed()) {
        txtSpeed.setText(Strings.getSpeedDisplay(getActivity(), locationInfo.getSpeed(),
                preferenceHelper.shouldDisplayImperialUnits()));

    } else {
        txtSpeed.setText(R.string.not_applicable);
    }

    if (locationInfo.hasBearing()) {

        float bearingDegrees = locationInfo.getBearing();
        String direction;

        direction = Strings.getBearingDescription(bearingDegrees, getActivity().getApplicationContext());

        txtDirection.setText(direction + "(" + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol) + ")");
    } else {
        txtDirection.setText(R.string.not_applicable);
    }

    if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
    }

    if (locationInfo.hasAccuracy()) {

        float accuracy = locationInfo.getAccuracy();
        txtAccuracy.setText(getString(R.string.accuracy_within, Strings.getDistanceDisplay(getActivity(),
                accuracy, preferenceHelper.shouldDisplayImperialUnits()), ""));

    } else {
        txtAccuracy.setText(R.string.not_applicable);
    }

    double distanceValue = Session.getTotalTravelled();
    txtTravelled.setText(Strings.getDistanceDisplay(getActivity(), distanceValue,
            preferenceHelper.shouldDisplayImperialUnits()) + " (" + Session.getNumLegs() + " points)");

    long startTime = Session.getStartTimeStamp();
    Date d = new Date(startTime);
    long currentTime = System.currentTimeMillis();

    String duration = Strings.getDescriptiveDurationString((int) (currentTime - startTime) / 1000,
            getActivity());

    DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
    DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity().getApplicationContext());
    txtTime.setText(duration + " (started at " + dateFormat.format(d) + " " + timeFormat.format(d) + ")");

}

From source file:desmoj.extensions.grafic.util.Plotter.java

/**
 * configure range axis ( lowerBound, upperBound, label, format ticks)
 * of time-series chart// w ww  . j  a v a 2  s.  c  om
 * @param numberAxis
 * @param label
 */
private void configureRangeAxis(NumberAxis numberAxis, String label) {
    double min = numberAxis.getLowerBound();
    double max = numberAxis.getUpperBound();
    Double delta = 0.01 * (max - min);
    numberAxis.setLowerBound(min - delta);
    numberAxis.setUpperBound(max + delta);

    numberAxis.setLabel(label);

    // format Ticks
    double fontHeight = numberAxis.getTickLabelFont().getLineMetrics("X", this.frc).getHeight();
    double maxTicks = this.paintPanel.getSize().height / fontHeight;
    int digits = Math.max(0, (int) -Math.floor(Math.log10((max - min) / maxTicks)));
    //System.out.println(fontHeight+"  "+digits+"  "+Math.log10((max - min)/ maxTicks));
    NumberFormat formatter = NumberFormat.getNumberInstance(this.locale);
    formatter.setMinimumFractionDigits(digits);
    formatter.setMaximumFractionDigits(digits);
    formatter.setGroupingUsed(true);
    numberAxis.setNumberFormatOverride(formatter);
}

From source file:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java

private void processCredit(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);//from   w w  w  .j  a  v a2  s . c  o m

    // Set the account
    String toAccount = mCursor.getString(TransactionsFragment.COLUMN_TO_ACCOUNT_TITLE);
    holder.mAccount.setText(toAccount);

    // Set the amount
    double toAmount = NumberUtils
            .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_AMOUNT) / 100.0);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String toCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_TO_CURRENCY);
    Currency toCurrency = Currency.getInstance(toCurrencyCode);
    format.setCurrency(toCurrency);
    format.setMaximumFractionDigits(toCurrency.getDefaultFractionDigits());
    holder.mAmount.setText(format.format(toAmount));
    holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));

    double toBalance = NumberUtils
            .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);
    holder.mRunningBalance.setText(format.format(toBalance));

    // Set the transaction type icon
    holder.mTypeIcon.setImageDrawable(
            DrawableHelper.tint(mContext, R.drawable.ic_call_received_black_24dp, R.color.colorGreen700));
}

From source file:ubic.gemma.core.apps.ShellDelegatingBlat.java

private synchronized void outputFile(final String outputPath, StopWatch overallWatch) {
    File outputFile = new File(outputPath);
    Long size = outputFile.length();
    NumberFormat nf = new DecimalFormat();
    nf.setMaximumFractionDigits(2);
    String minutes = TimeUtil.getMinutesElapsed(overallWatch);
    ShellDelegatingBlat.log//w  ww.  j a  v a  2  s . c om
            .info("BLAT output so far: " + nf.format(size / 1024.0) + " kb (" + minutes + " minutes elapsed)");

}

From source file:com.commander4j.util.JUtility.java

public static String bigDecimaltoString(BigDecimal bd) {
    String result = "";
    NumberFormat nf1 = NumberFormat.getInstance();

    nf1 = NumberFormat.getInstance();
    nf1.setMinimumFractionDigits(3);//from   ww w.  j  a va2  s  . c o m
    nf1.setMaximumFractionDigits(3);
    result = nf1.format(bd);

    return result;
}

From source file:org.squale.squaleweb.util.graph.BubbleMaker.java

/**
 * Affichage sous la forme de sous-titres de la rpartition des mthodes - Maintenable et structur, - Maintenable
 * mais mal structur - Difficilement maintenable mais structur - Difficilement maintenable et mal structur
 * //from   w ww  .j  a v  a  2s. c  o m
 * @param pChart graphe de type Bubble
 */
private void displayRepartitionSubtitles(JFreeChart pChart) {
    double percentTopLeft = 0;
    double percentTopRight = 0;
    double percentBottomLeft = 0;
    double percentBottomRight = 0;
    int totalMethods = (int) (totalTopLeft + totalTopRight + totalBottomLeft + totalBottomRight);
    if (totalMethods > 0) {
        final int oneHundred = 100;
        // haut gauche : difficilement maintenable mais structur
        percentTopLeft = totalTopLeft * oneHundred / totalMethods;
        // haut droit : difficilement maintenable et mal structur
        percentTopRight = totalTopRight * oneHundred / totalMethods;
        // Bas gauche : maintenable et structur
        percentBottomLeft = totalBottomLeft * oneHundred / totalMethods;
        // Bas droit : maintenable mais mal structur
        percentBottomRight = totalBottomRight * oneHundred / totalMethods;
    }
    // Formatage des zones d'affichage
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setMaximumFractionDigits(1);
    numberFormat.setMinimumFractionDigits(1);
    // Ajout du sous-titre de rpartition des mthodes avec le pourcentage correspondant : partie suprieure, coin
    // gauche et droit
    StringBuffer stringBufferTop = new StringBuffer();
    stringBufferTop.append(WebMessages.getString(locale, "bubble.project.subtitle.topLeft") + " "
            + numberFormat.format(percentTopLeft) + "%     ");
    stringBufferTop.append(WebMessages.getString(locale, "bubble.project.subtitle.topRight") + " "
            + numberFormat.format(percentTopRight) + "%");
    TextTitle subtitleTop = new TextTitle(stringBufferTop.toString());

    // Ajout du sous-titre de rpartition des mthodes avec le pourcentage correspondant : partie infrieure, coin
    // gauche et droit
    StringBuffer stringBufferBottom = new StringBuffer();
    stringBufferBottom.append(WebMessages.getString(locale, "bubble.project.subtitle.bottomLeft") + " "
            + numberFormat.format(percentBottomLeft) + "%     ");
    stringBufferBottom.append(WebMessages.getString(locale, "bubble.project.subtitle.bottomRight") + " "
            + numberFormat.format(percentBottomRight) + "%");
    TextTitle subtitleBottom = new TextTitle(stringBufferBottom.toString());

    // Les rpartitions sont ajoutes sous la forme de sous-menus
    subtitleBottom.setPosition(RectangleEdge.BOTTOM);
    pChart.addSubtitle(subtitleBottom);
    subtitleTop.setPosition(RectangleEdge.BOTTOM);
    pChart.addSubtitle(subtitleTop);
}

From source file:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java

private void processDebit(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);//from  w w w.  j  a  va 2 s.  com

    // Set the account
    String fromAccount = mCursor.getString(TransactionsFragment.COLUMN_FROM_ACCOUNT_TITLE);
    holder.mAccount.setText(fromAccount);

    // Set the amount
    double fromAmount = NumberUtils
            .roundToTwoPlaces(0 - mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String fromCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_FROM_CURRENCY);
    Currency fromCurrency = Currency.getInstance(fromCurrencyCode);
    format.setCurrency(fromCurrency);
    format.setMaximumFractionDigits(fromCurrency.getDefaultFractionDigits());
    holder.mAmount.setText(format.format(fromAmount));
    holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));

    double fromBalance = NumberUtils
            .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_BALANCE) / 100.0);
    holder.mRunningBalance.setText(format.format(fromBalance));

    // Set the transaction type icon
    holder.mTypeIcon.setImageDrawable(
            DrawableHelper.tint(mContext, R.drawable.ic_call_made_black_24dp, R.color.colorRed700));
}

From source file:fr.cirad.mgdb.exporting.markeroriented.GFFExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*from  w  ww. java 2s.  c om*/
        }

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);
    ArrayList<String> individualList = new ArrayList<String>();
    for (int i = 0; i < sampleIDs.size(); i++) {
        Individual individual = individuals.get(i);
        if (!individualList.contains(individual.getId())) {
            individualList.add(individual.getId());
        }
    }

    String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".gff3"));
    String header = "##gff-version 3" + LINE_SEPARATOR;
    zos.write(header.getBytes());

    TreeMap<String, String> typeToOntology = new TreeMap<String, String>();
    typeToOntology.put(Type.SNP.toString(), "SO:0000694");
    typeToOntology.put(Type.INDEL.toString(), "SO:1000032");
    typeToOntology.put(Type.MIXED.toString(), "SO:0001059");
    typeToOntology.put(Type.SYMBOLIC.toString(), "SO:0000109");
    typeToOntology.put(Type.MNP.toString(), "SO:0001059");

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    short nProgress = 0, nPreviousProgress = 0;
    long nLoadedMarkerCount = 0;

    while (markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
        LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                mongoTemplate, sampleIDs, currentMarkers, true,
                null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
        for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
        {
            Comparable variantId = variant.getId();
            List<String> variantDataOrigin = new ArrayList<String>();

            Map<String, Integer> gqValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, Integer> dpValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
            List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":");
            if (chromAndPos.size() == 0)
                LOG.warn("Chromosomal position not found for marker " + variantId);
            // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR);
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(variantId);
                if (syn != null)
                    variantId = syn;
            }

            Collection<VariantRunData> runs = variantsAndRuns.get(variant);
            if (runs != null)
                for (VariantRunData run : runs)
                    for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                        SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                        String individualId = individuals
                                .get(sampleIDs.indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                .getId();

                        Integer gq = null;
                        try {
                            gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ);
                        } catch (Exception ignored) {
                        }
                        if (gq != null && gq < nMinimumGenotypeQuality)
                            continue;

                        Integer dp = null;
                        try {
                            dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP);
                        } catch (Exception ignored) {
                        }
                        if (dp != null && dp < nMinimumReadDepth)
                            continue;

                        String gtCode = sampleGenotype.getCode();
                        List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                        if (storedIndividualGenotypes == null) {
                            storedIndividualGenotypes = new ArrayList<String>();
                            individualGenotypes.put(individualId, storedIndividualGenotypes);
                        }
                        storedIndividualGenotypes.add(gtCode);
                    }

            zos.write((chromAndPos.get(0) + "\t" + StringUtils.join(variantDataOrigin, ";") /*source*/ + "\t"
                    + typeToOntology.get(variant.getType()) + "\t" + Long.parseLong(chromAndPos.get(1)) + "\t"
                    + Long.parseLong(chromAndPos.get(1)) + "\t" + "." + "\t" + "+" + "\t" + "." + "\t")
                            .getBytes());
            Comparable syn = markerSynonyms == null ? null : markerSynonyms.get(variant.getId());
            zos.write(("ID=" + variant.getId() + ";" + (syn != null ? "Name=" + syn + ";" : "") + "alleles="
                    + StringUtils.join(variant.getKnownAlleleList(), "/") + ";" + "refallele="
                    + variant.getKnownAlleleList().get(0) + ";").getBytes());

            for (int j = 0; j < individualList
                    .size(); j++ /* we use this list because it has the proper ordering*/) {

                NumberFormat nf = NumberFormat.getInstance(Locale.US);
                nf.setMaximumFractionDigits(4);
                HashMap<String, Integer> compt1 = new HashMap<String, Integer>();
                int highestGenotypeCount = 0;
                int sum = 0;

                String individualId = individualList.get(j);
                List<String> genotypes = individualGenotypes.get(individualId);
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes

                String mostFrequentGenotype = null;
                if (genotypes != null)
                    for (String genotype : genotypes) {
                        if (genotype.length() == 0)
                            continue; /* skip missing genotypes */

                        int count = 0;
                        for (String t : variant.getAllelesFromGenotypeCode(genotype)) {
                            for (String t1 : variant.getKnownAlleleList()) {
                                if (t.equals(t1) && !(compt1.containsKey(t1))) {
                                    count++;
                                    compt1.put(t1, count);
                                } else if (t.equals(t1) && compt1.containsKey(t1)) {
                                    if (compt1.get(t1) != 0) {
                                        count++;
                                        compt1.put(t1, count);
                                    } else
                                        compt1.put(t1, count);
                                } else if (!(compt1.containsKey(t1))) {
                                    compt1.put(t1, 0);
                                }
                            }
                        }
                        for (int countValue : compt1.values()) {
                            sum += countValue;
                        }

                        int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                        if (gtCount > highestGenotypeCount) {
                            highestGenotypeCount = gtCount;
                            mostFrequentGenotype = genotype;
                        }
                        genotypeCounts.put(genotype, gtCount);
                    }

                List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>()
                        : variant.getAllelesFromGenotypeCode(mostFrequentGenotype);

                if (alleles.size() != 0) {
                    zos.write(("acounts=" + individualId + ":").getBytes());

                    for (String knowAllelesCompt : compt1.keySet()) {
                        zos.write(
                                (knowAllelesCompt + " " + nf.format(compt1.get(knowAllelesCompt) / (float) sum)
                                        + " " + compt1.get(knowAllelesCompt) + " ").getBytes());
                    }
                    zos.write((alleles.size() + ";").getBytes());
                }
                if (genotypeCounts.size() > 1) {
                    Comparable sVariantId = markerSynonyms != null ? markerSynonyms.get(variant.getId())
                            : variant.getId();
                    warningFileWriter.write("- Dissimilar genotypes found for variant "
                            + (sVariantId == null ? variant.getId() : sVariantId) + ", individual "
                            + individualId + ". Exporting most frequent: " + StringUtils.join(alleles, ",")
                            + "\n");
                }
            }
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            //            if (nProgress%5 == 0)
            //               LOG.info("========================= exportData: " + nProgress + "% =========================" + (System.currentTimeMillis() - before)/1000 + "s");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:com.liusoft.dlog4j.velocity.VelocityTool.java

/**
 * (??)/*from  w  w  w.j a va 2 s .  c o m*/
 * ?,?
 * @return
 */
public String festival() {
    long[] ds = LunarCalendar.today();
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(2);
    String nongli = nf.format(ds[1]) + nf.format(ds[2]);
    Calendar cal = Calendar.getInstance();
    String yangli = nf.format(cal.get(Calendar.MONTH) + 1) + nf.format(cal.get(Calendar.DATE));
    //System.out.printf("nongli=%s,yangli=%s\r\n",nongli,yangli);
    String f_nl = getMessage(request, "festival", 'Y' + nongli);
    String f_yl = getMessage(request, "festival", yangli);
    if (f_nl != null && f_yl != null)
        return f_yl + "," + f_nl;
    if (f_nl != null)
        return f_nl;
    if (f_yl != null)
        return f_yl;
    return null;
}