Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

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

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

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

public void displayLocationInfo(Location locationInfo) {
    if (locationInfo == null) {
        return;//  www  .j  a  v a2  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:io.plaidapp.ui.DribbbleShot.java

void bindShot(final boolean postponeEnterTransition) {
    final Resources res = getResources();

    // load the main image
    final int[] imageSize = shot.images.bestSize();
    Glide.with(this).load(shot.images.best()).listener(shotLoadListener)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE)
            .override(imageSize[0], imageSize[1]).into(imageView);
    imageView.setOnClickListener(shotClick);
    shotSpacer.setOnClickListener(shotClick);

    if (postponeEnterTransition)
        postponeEnterTransition();//  w  w w  . j  av  a  2 s  .co m
    imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            calculateFabPosition();
            if (postponeEnterTransition)
                startPostponedEnterTransition();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ((FabOverlapTextView) title).setText(shot.title);
    } else {
        ((TextView) title).setText(shot.title);
    }
    if (!TextUtils.isEmpty(shot.description)) {
        final Spanned descText = shot.getParsedDescription(
                ContextCompat.getColorStateList(this, R.color.dribbble_links),
                ContextCompat.getColor(this, R.color.dribbble_link_highlight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ((FabOverlapTextView) description).setText(descText);
        } else {
            HtmlUtils.setTextWithNiceLinks((TextView) description, descText);
        }
    } else {
        description.setVisibility(View.GONE);
    }
    NumberFormat nf = NumberFormat.getInstance();
    likeCount.setText(
            res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count)));
    likeCount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) likeCount.getCompoundDrawables()[1]).start();
            if (shot.likes_count > 0) {
                PlayerSheet.start(DribbbleShot.this, shot);
            }
        }
    });
    if (shot.likes_count == 0) {
        likeCount.setBackground(null); // clear touch ripple if doesn't do anything
    }
    viewCount.setText(
            res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count)));
    viewCount.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) viewCount.getCompoundDrawables()[1]).start();
        }
    });
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((AnimatedVectorDrawable) share.getCompoundDrawables()[1]).start();
            new ShareDribbbleImageTask(DribbbleShot.this, shot).execute();
        }
    });
    if (shot.user != null) {
        playerName.setText(shot.user.name.toLowerCase());
        Glide.with(this).load(shot.user.getHighQualityAvatarUrl()).transform(circleTransform)
                .placeholder(R.drawable.avatar_placeholder).override(largeAvatarSize, largeAvatarSize)
                .into(playerAvatar);
        View.OnClickListener playerClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent player = new Intent(DribbbleShot.this, PlayerActivity.class);
                if (shot.user.shots_count > 0) { // legit user object
                    player.putExtra(PlayerActivity.EXTRA_PLAYER, shot.user);
                } else {
                    // search doesn't fully populate the user object,
                    // in this case send the ID not the full user
                    player.putExtra(PlayerActivity.EXTRA_PLAYER_NAME, shot.user.username);
                    player.putExtra(PlayerActivity.EXTRA_PLAYER_ID, shot.user.id);
                }
                ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(DribbbleShot.this,
                        playerAvatar, getString(R.string.transition_player_avatar));
                startActivity(player, options.toBundle());
            }
        };
        playerAvatar.setOnClickListener(playerClick);
        playerName.setOnClickListener(playerClick);
        if (shot.created_at != null) {
            shotTimeAgo
                    .setText(
                            DateUtils
                                    .getRelativeTimeSpanString(shot.created_at.getTime(),
                                            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS)
                                    .toString().toLowerCase());
        }
    } else {
        playerName.setVisibility(View.GONE);
        playerAvatar.setVisibility(View.GONE);
        shotTimeAgo.setVisibility(View.GONE);
    }

    commentAnimator = new CommentAnimator();
    commentsList.setItemAnimator(commentAnimator);
    adapter = new CommentsAdapter(shotDescription, commentFooter, shot.comments_count,
            getResources().getInteger(R.integer.comment_expand_collapse_duration));
    commentsList.setAdapter(adapter);
    commentsList.addItemDecoration(new InsetDividerDecoration(CommentViewHolder.class,
            res.getDimensionPixelSize(R.dimen.divider_height), res.getDimensionPixelSize(R.dimen.keyline_1),
            ContextCompat.getColor(this, R.color.divider)));
    if (shot.comments_count != 0) {
        loadComments();
    }
    checkLiked();
}

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

public void displayLocationInfo(Location locationInfo) {
    showPreferencesSummary();/*from w  w  w  .j  a v  a 2s .  co m*/

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    EditText txtLatitude = (EditText) rootView.findViewById(R.id.simple_lat_text);
    txtLatitude.setText(String.valueOf(nf.format(locationInfo.getLatitude())) + ", "
            + String.valueOf(nf.format(locationInfo.getLongitude())));

    nf.setMaximumFractionDigits(3);

    ImageView imgAccuracy = (ImageView) rootView.findViewById(R.id.simpleview_imgAccuracy);
    clearColor(imgAccuracy);

    if (locationInfo.hasAccuracy()) {

        TextView txtAccuracy = (TextView) rootView.findViewById(R.id.simpleview_txtAccuracy);
        float accuracy = locationInfo.getAccuracy();
        txtAccuracy.setText(Strings.getDistanceDisplay(getActivity(), accuracy,
                preferenceHelper.shouldDisplayImperialUnits()));

        if (accuracy > 500) {
            setColor(imgAccuracy, IconColorIndicator.Warning);
        }

        if (accuracy > 900) {
            setColor(imgAccuracy, IconColorIndicator.Bad);
        } else {
            setColor(imgAccuracy, IconColorIndicator.Good);
        }
    }

    ImageView imgAltitude = (ImageView) rootView.findViewById(R.id.simpleview_imgAltitude);
    clearColor(imgAltitude);

    if (locationInfo.hasAltitude()) {
        setColor(imgAltitude, IconColorIndicator.Good);
        TextView txtAltitude = (TextView) rootView.findViewById(R.id.simpleview_txtAltitude);

        txtAltitude.setText(Strings.getDistanceDisplay(getActivity(), locationInfo.getAltitude(),
                preferenceHelper.shouldDisplayImperialUnits()));
    }

    ImageView imgSpeed = (ImageView) rootView.findViewById(R.id.simpleview_imgSpeed);
    clearColor(imgSpeed);

    if (locationInfo.hasSpeed()) {

        setColor(imgSpeed, IconColorIndicator.Good);

        TextView txtSpeed = (TextView) rootView.findViewById(R.id.simpleview_txtSpeed);
        txtSpeed.setText(Strings.getSpeedDisplay(getActivity(), locationInfo.getSpeed(),
                preferenceHelper.shouldDisplayImperialUnits()));
    }

    ImageView imgDirection = (ImageView) rootView.findViewById(R.id.simpleview_imgDirection);
    clearColor(imgDirection);

    if (locationInfo.hasBearing()) {
        setColor(imgDirection, IconColorIndicator.Good);
        imgDirection.setRotation(locationInfo.getBearing());

        TextView txtDirection = (TextView) rootView.findViewById(R.id.simpleview_txtDirection);
        txtDirection.setText(
                String.valueOf(Math.round(locationInfo.getBearing())) + getString(R.string.degree_symbol));
    }

    TextView txtDuration = (TextView) rootView.findViewById(R.id.simpleview_txtDuration);

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

    txtDuration.setText(Strings.getTimeDisplay(getActivity(), currentTime - startTime));

    double distanceValue = Session.getTotalTravelled();

    TextView txtPoints = (TextView) rootView.findViewById(R.id.simpleview_txtPoints);
    TextView txtTravelled = (TextView) rootView.findViewById(R.id.simpleview_txtDistance);

    txtTravelled.setText(Strings.getDistanceDisplay(getActivity(), distanceValue,
            preferenceHelper.shouldDisplayImperialUnits()));
    txtPoints.setText(Session.getNumLegs() + " " + getString(R.string.points));

    String providerName = locationInfo.getProvider();
    if (!providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
        setSatelliteCount(-1);
    }
}

From source file:edu.cornell.med.icb.goby.modes.SplitTranscriptsMode.java

/**
 * Get a number formatter to print leading zeros up to n.
 *
 * @param n The largest number that will be formatted
 * @return the NumberFormat for n// w ww  . j  a  v  a  2  s  .  c  o m
 */
public NumberFormat getNumberFormatter(final int n) {
    assert n >= 0 : "n must be non-negative";
    final int numDigits;
    if (n == 0) {
        numDigits = 1;
    } else {
        numDigits = 1 + (int) (Math.log10(n));
    }

    final NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    numberFormat.setMinimumIntegerDigits(numDigits);
    return numberFormat;
}

From source file:com.levien.audiobuffersize.AudioBufferSize.java

JitterMeasurement analyzeDrift(double[] arr, double forceRate) {
    final int startupSkip = 100;
    int n = arr.length / 4;
    // Do linear regression to find timing drift
    double xys = 0, xs = 0, ys = 0, x2s = 0;
    int count = n - startupSkip;
    for (int i = startupSkip; i < n; i++) {
        double x = i;
        double y = arr[i];
        xys += x * y;/* w w w  . j  a  v  a  2 s  .co  m*/
        xs += x;
        ys += y;
        x2s += x * x;
    }
    double beta = (count * xys - xs * ys) / (count * x2s - xs * xs);
    double jitRate = forceRate == 0 ? beta : forceRate;
    //double alpha = (ys - beta * xs) / count;
    double minJit = 0;
    double maxJit = 0;
    for (int i = startupSkip; i < n; i++) {
        double err = jitRate * i - arr[i];
        if (i == startupSkip || err < minJit)
            minJit = err;
        if (i == startupSkip || err > maxJit)
            maxJit = err;
    }
    JitterMeasurement jm = new JitterMeasurement();
    jm.rate = beta;
    jm.jitter = maxJit - minJit;
    NumberFormat f = NumberFormat.getInstance();
    f.setMinimumFractionDigits(3);
    f.setMaximumFractionDigits(3);
    logUI("ms per tick = " + f.format(jm.rate * 1000) + "; jitter (lr) = " + f.format(jm.jitter * 1000));
    return jm;
}

From source file:com.rockhoppertech.music.Note.java

/**
 * <code>toString</code>/*from   w ww  . j  a v a2 s . c o  m*/
 * 
 * @return a <code>String</code> value
 */
@Override
public String toString() {
    final StringBuilder sb = new StringBuilder();
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    nf.setMaximumIntegerDigits(3);
    nf.setMinimumIntegerDigits(3);
    sb.append(this.getClass().getSimpleName()).append('[');
    sb.append("startBeat: ").append(nf.format(startBeat));
    sb.append(" pitch: ").append(pitch);
    sb.append(" dur: ").append(nf.format(duration));
    sb.append(" : ").append(getDurationString());

    sb.append(" endBeat: ").append(nf.format(endBeat));
    sb.append(" midinum: ").append(pitch.getMidiNumber());
    sb.append(" rest: ").append(rest);
    sb.append(']');
    return sb.toString();
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.OverlaidStackedBarLine.java

public JFreeChart createChart(DatasetMap datasets) {

    // create the first renderer...

    CategoryPlot plot = new CategoryPlot();
    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = new NumberAxis(getValueLabel());
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis/* w w  w.j a  v  a2s  .  co m*/
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);
    plot.setRangeAxis(rangeAxis);
    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    CategoryAxis domainAxis = new CategoryAxis(getCategoryLabel());
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    plot.setDomainAxis(domainAxis);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeGridlinesVisible(true);
    plot.setDomainGridlinesVisible(true);

    DefaultCategoryDataset datasetBar = (DefaultCategoryDataset) datasets.getDatasets().get("stackedbar");

    //I create one bar renderer and one line

    MyStandardCategoryItemLabelGenerator generator = null;
    if (additionalLabels) {
        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
    }

    if (useBars) {
        CategoryItemRenderer barRenderer = new StackedBarRenderer();

        if (maxBarWidth != null) {
            ((BarRenderer) barRenderer).setMaximumBarWidth(maxBarWidth.doubleValue());
        }

        if (additionalLabels) {
            barRenderer.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }
            barRenderer.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            barRenderer.setBaseItemLabelPaint(styleValueLabels.getColor());
            barRenderer.setBaseItemLabelsVisible(true);
            barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));

        }

        if (colorMap != null) {
            for (Iterator iterator = datasetBar.getRowKeys().iterator(); iterator.hasNext();) {
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;
                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetBar.getRowIndex(labelName);
                } else
                    index = datasetBar.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    barRenderer.setSeriesPaint(index, color);
                }
            }
        }
        // add tooltip if enabled
        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            barRenderer.setToolTipGenerator(generatorToolTip);
        }

        //defines url for drill
        boolean document_composition = false;
        if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
            document_composition = true;

        logger.debug("Calling Url Generation");

        MyCategoryUrlGenerator mycatUrl = null;
        if (super.rootUrl != null) {
            logger.debug("Set MycatUrl");
            mycatUrl = new MyCategoryUrlGenerator(super.rootUrl);

            mycatUrl.setDocument_composition(document_composition);
            mycatUrl.setCategoryUrlLabel(super.categoryUrlName);
            mycatUrl.setSerieUrlLabel(super.serieUrlname);
            mycatUrl.setDrillDocTitle(drillDocTitle);
            mycatUrl.setTarget(target);
        }
        if (mycatUrl != null) {
            barRenderer.setItemURLGenerator(mycatUrl);
        }

        plot.setDataset(1, datasetBar);
        plot.setRenderer(1, barRenderer);

    }

    if (useLines) {

        LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
        //lineRenderer.setShapesFilled(false);
        lineRenderer.setShapesFilled(true);
        if (additionalLabels) {
            lineRenderer.setBaseItemLabelGenerator(generator);
            lineRenderer.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            lineRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            lineRenderer.setBaseItemLabelsVisible(true);
        }

        DefaultCategoryDataset datasetLine = (DefaultCategoryDataset) datasets.getDatasets().get("line");

        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            lineRenderer.setToolTipGenerator(generatorToolTip);
        }

        if (colorMap != null) {
            for (Iterator iterator = datasetLine.getRowKeys().iterator(); iterator.hasNext();) {
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetLine.getRowIndex(labelName);
                } else
                    index = datasetLine.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    lineRenderer.setSeriesPaint(index, color);
                }
            }
        }
        plot.setDataset(0, datasetLine);
        plot.setRenderer(0, lineRenderer);
    }

    if (secondAxis) {
        NumberAxis na = new NumberAxis(secondAxisLabel);
        na.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setLabelPaint(styleXaxesLabels.getColor());
        na.setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setTickLabelPaint(styleXaxesLabels.getColor());
        na.setUpperMargin(0.10);
        if (rangeIntegerValues == true) {
            na.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        }
        na.setNumberFormatOverride(nf);
        plot.setRangeAxis(1, na);
        plot.mapDatasetToRangeAxis(0, 1);
    }

    //plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    JFreeChart chart = new JFreeChart(plot);
    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    chart.setBackgroundPaint(Color.white);

    if (legend == true)
        drawLegend(chart);
    return chart;

}

From source file:gate.twitter.HashtagTokenizer.java

@Override
public void execute() throws ExecutionException {
    AnnotationSet inputAS = document.getAnnotations(inputASName);
    AnnotationSet outputAS = document.getAnnotations(outputASName);

    FeatureMap features = Factory.newFeatureMap();

    long startTime = System.currentTimeMillis();
    fireStatusChanged("Tokenizing Hashtags: " + document.getName());
    fireProgressChanged(0);/*from w w  w  .  jav a 2s .  c  o  m*/
    int count = 0;

    // get all the lookups we are going to use for decomposition...
    AnnotationSet lookups = new AnnotationSetImpl(document);

    try {
        // run the gazetteer to produce the HashtagLookup annotations
        gaz.setParameterValue("annotationSetName", inputASName);
        gaz.setDocument(document);
        gaz.execute();

        // get all the hashtags
        AnnotationSet hashtags = inputAS.get("Hashtag");

        for (Annotation hashtag : inputAS.get("Hashtag")) {
            // for each hashtag in the document...

            AnnotationSet contained = inputAS.getContained(hashtag.getStartNode().getOffset(),
                    hashtag.getEndNode().getOffset());

            //clear away any left overs from previous tags
            lookups.clear();

            // which are the HashtagLookup
            lookups.addAll(contained.get("HashtagLookup"));

            // any other Lookups the user has generated
            lookups.addAll(contained.get("Lookup"));

            // and any number tokens
            features = Factory.newFeatureMap();
            features.put("kind", "number");
            lookups.addAll(contained.get("Token", features));

            // the _ appears to be allowed so add them as well
            features = Factory.newFeatureMap();
            features.put("string", "_");
            lookups.addAll(contained.get("Token", features));

            if (isInterrupted()) {
                throw new ExecutionInterruptedException(
                        "The execution of the hashtag tokenizer has been abruptly interrupted!");
            }

            // this will hold the best we have seen so far
            List<List<Annotation>> fewestTokens = new ArrayList<List<Annotation>>();

            // get all the lookups that start at the beginning of the hashtag
            List<Annotation> start = sort(
                    getAnnotationsAtOffset(lookups, hashtag.getStartNode().getOffset() + 1));

            for (Annotation a : start) {
                // for each lookup search for a valid tokenization
                List<List<Annotation>> found = search(lookups, hashtag.getEndNode().getOffset(), a);

                if (found != null) {
                    // if we found a contender and it's the best so far store it
                    if (fewestTokens.isEmpty()) {
                        fewestTokens.addAll(found);
                    } else if (found.get(0).size() == fewestTokens.get(0).size()) {
                        fewestTokens.addAll(found);
                    } else if (found.get(0).size() < fewestTokens.get(0).size()) {
                        fewestTokens.clear();
                        fewestTokens.addAll(found);
                    }
                }
            }

            if (debug && fewestTokens.size() > 1) {
                System.out.println(stringFor(document, hashtag));
                display(fewestTokens);
            }

            if (fewestTokens.isEmpty()) {
                // if we didn't find any sensible tokenizations then let's see if the
                // hashtag is mized case

                String tagText = stringFor(document, hashtag).substring(1);
                if ("mixedCaps".equals(getTokenType(tagText)[1])) {
                    // if we have a mixed case hahstag then let's assume it is
                    // CamelCased and split it accordingly

                    // TODO think about camel case which includes numbers

                    // a list to hold the tokens
                    List<Annotation> found = new ArrayList<Annotation>();

                    // start looking for token breaks aftert the initial #
                    long begin = hashtag.getStartNode().getOffset() + 1;

                    for (String token : tagText.split("((?<=[a-z])(?=[A-Z]))|((?<=[A-Z]{2,})(?=[a-z]))")) {
                        // split the token at the case changes...

                        // create the annotation in the Lookup set and add it to the found
                        // list
                        found.add(lookups.get(lookups.add(begin, (begin += token.length()), "CamelToken",
                                Factory.newFeatureMap())));
                    }

                    // record the tokenization so we can process it later
                    fewestTokens.add(found);
                }

            }

            if (!fewestTokens.isEmpty()) {
                // if we found a valid tokenization then...

                // remove any existing Token annotations
                inputAS.removeAll(inputAS.get("Token").getContained(hashtag.getStartNode().getOffset(),
                        hashtag.getEndNode().getOffset()));

                // create a punctuation Token over the #
                features = Factory.newFeatureMap();
                features.put("string", "#");
                features.put("length", "1");
                features.put("kind", "punctuation");
                outputAS.add(hashtag.getStartNode().getOffset(), hashtag.getStartNode().getOffset() + 1,
                        "Token", features);

                // let's assume that the first one we found is best
                int prefered = 0;

                for (int i = 0; i < fewestTokens.size(); ++i) {
                    // check those we have found and skip over any that contain single
                    // letter or mixed case words

                    boolean okay = true;
                    for (Annotation a : fewestTokens.get(i)) {
                        // single letter words are not great
                        if (a.getEndNode().getOffset() - a.getStartNode().getOffset() == 1)
                            okay = false;
                    }

                    if (okay) {
                        // if it contains neither a single letter word or a mixed case
                        // word then we should definitely prefer this one
                        prefered = i;
                        break;
                    }
                }

                for (Annotation a : fewestTokens.get(prefered)) {
                    // for each new token...

                    // find where it starts/ends and its length
                    long startOffset = a.getStartNode().getOffset();
                    long endOffset = a.getEndNode().getOffset();
                    String length = Long.toString(endOffset - startOffset);

                    // get the actual text
                    String string = stringFor(document, a);

                    // work out what kind of token it is and if it is a word
                    // what its orthography is
                    String[] tokenType = getTokenType(string);
                    String kind = tokenType[0];
                    String orth = tokenType[1];

                    // create the new Token annotation
                    features = Factory.newFeatureMap();
                    features.put("string", string);
                    features.put("length", length);
                    features.put("kind", kind);
                    if (orth != null)
                        features.put("orth", orth);
                    outputAS.add(startOffset, endOffset, "Token", features);

                    if (debug) {
                        // for debug purposes add a matching set of HashtagToken
                        // annotations
                        features = Factory.newFeatureMap();
                        features.put("string", string);
                        features.put("length", length);
                        features.put("kind", kind);
                        if (orth != null)
                            features.put("orth", orth);
                        outputAS.add(startOffset, endOffset, "HashtagToken", features);
                    }
                }
            } else if (debug) {
                System.err.println(stringFor(document, hashtag));

                AnnotationSet tokens = inputAS.get("Token").getContained(hashtag.getStartNode().getOffset() + 1,
                        hashtag.getEndNode().getOffset());

                for (Annotation token : tokens) {

                    features = Factory.newFeatureMap();
                    features.putAll(token.getFeatures());
                    outputAS.add(token.getStartNode().getOffset(), token.getEndNode().getOffset(),
                            "HashtagToken", features);
                }
            }

            fireProgressChanged(count++ * 100 / hashtags.size());
        }

        fireProcessFinished();
        fireStatusChanged("Hashtags in " + document.getName() + " tokenized in "
                + NumberFormat.getInstance().format((double) (System.currentTimeMillis() - startTime) / 1000)
                + " seconds!");
    } catch (InvalidOffsetException e) {
        throw new ExecutionException(e);
    } catch (ResourceInstantiationException e) {
        throw new ExecutionException(e);
    } finally {
        gaz.setDocument(null);

        if (!debug) {
            inputAS.removeAll(inputAS.get("HashtagLookup"));
        }
    }
}

From source file:org.apache.ambari.scom.SQLPropertyProvider.java

private Map<MetricDefinition, List<DataPoint>> getMetric(Set<MetricDefinition> metricDefinitionSet,
        Statement statement) throws SystemException {
    Map<MetricDefinition, List<DataPoint>> results = new HashMap<MetricDefinition, List<DataPoint>>();
    try {//from   w w  w. ja  v a2 s.  com
        StringBuilder query = new StringBuilder();
        Set<String> recordTypeContexts = new HashSet<String>();
        Set<String> recordTypeNamess = new HashSet<String>();
        Set<String> tagPairsPatterns = new HashSet<String>();
        Set<String> nodeNames = new HashSet<String>();
        Set<String> serviceNames = new HashSet<String>();
        Set<String> metricNames = new HashSet<String>();
        long startTime = 0, endTime = 0;
        for (MetricDefinition metricDefinition : metricDefinitionSet) {
            if (metricDefinition.getRecordTypeContext() == null || metricDefinition.getRecordTypeName() == null
                    || metricDefinition.getNodeName() == null) {
                continue;
            }

            recordTypeContexts.add(metricDefinition.getRecordTypeContext());
            recordTypeNamess.add(metricDefinition.getRecordTypeName());
            tagPairsPatterns.add(metricDefinition.getTagPairsPattern());
            nodeNames.add(metricDefinition.getNodeName());
            serviceNames.add(metricDefinition.getServiceName());
            metricNames.add(metricDefinition.getMetricName());
            startTime = metricDefinition.getStartTime();
            endTime = metricDefinition.getEndTime();
        }

        for (String tagPairsPattern : tagPairsPatterns) {
            if (query.length() != 0) {
                query.append("\nUNION\n");
            }
            query.append(String.format(GET_METRICS_STATEMENT,
                    "'" + StringUtils.join(recordTypeContexts, "','") + "'",
                    "'" + StringUtils.join(recordTypeNamess, "','") + "'", "'%" + tagPairsPattern + "%'",
                    "'" + StringUtils.join(nodeNames, "','") + "'",
                    "'" + StringUtils.join(serviceNames, "','") + "'", startTime, endTime,
                    "'" + StringUtils.join(metricNames, "','") + "'"));
        }

        ResultSet rs = null;
        if (query.length() != 0) {
            rs = statement.executeQuery(query.toString());
        }

        if (rs != null) {
            //(RecordTimeStamp bigint, MetricValue NVARCHAR(512))
            while (rs.next()) {
                MetricDefinition metricDefinition = new MetricDefinition(rs.getString("RecordTypeContext"),
                        rs.getString("RecordTypeName"), rs.getString("TagPairs"), rs.getString("MetricName"),
                        rs.getString("ServiceName"), rs.getString("NodeName"));
                ParsePosition parsePosition = new ParsePosition(0);
                NumberFormat numberFormat = NumberFormat.getInstance();
                Number parsedNumber = numberFormat.parse(rs.getNString("MetricValue"), parsePosition);
                if (results.containsKey(metricDefinition)) {
                    results.get(metricDefinition)
                            .add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                } else {
                    List<DataPoint> dataPoints = new ArrayList<DataPoint>();
                    dataPoints.add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                    results.put(metricDefinition, dataPoints);
                }
            }
        }
    } catch (SQLException e) {
        throw new SystemException("Error during getMetric call : caught exception - ", e);
    }
    return results;
}

From source file:org.kalypso.ogc.sensor.timeseries.TimeseriesUtils.java

/**
 * Returns the adequate NumberFormat for the given format-string. It currently only supports formats of the form %X.Yf
 * where actually only the Y is used to build a NumberFormat with Y minimum/maximum-fraction-digits.
 * <p>//www  .  ja v a 2  s. c o m
 * The plan is, once we'll be using JDK 5.0, we'll try to replace this with the built-in functionality provided with
 * formated printing.
 * <p>
 * TODO once on JDK 5.0 use formated printing if possible. Note that some refactoring might need to be done since we
 * currently work with NumberFormats.
 */
public static synchronized NumberFormat getNumberFormat(final String format) {
    final NumberFormat nf = FORMAT_MAP.get(format);
    if (nf != null)
        return nf;

    if ("%d".equals(format)) //$NON-NLS-1$
    {
        final NumberFormat wf = NumberFormat.getIntegerInstance();
        wf.setGroupingUsed(false);
        FORMAT_MAP.put(format, wf);
        return wf;
    }

    // parse the format spec and only take the min-fraction-digit part
    final String regex = "%([0-9]*)\\.?([0-9]*)f"; //$NON-NLS-1$
    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher(format);
    if (matcher.matches()) {
        final String minfd = matcher.group(2);

        final NumberFormat wf = NumberFormat.getInstance();
        final int intValue = Integer.valueOf(minfd).intValue();
        wf.setMinimumFractionDigits(intValue);
        wf.setMaximumFractionDigits(intValue);
        FORMAT_MAP.put(format, wf);

        return wf;
    }

    return getDefaultFormat();
}