Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

In this page you can find the example usage for java.lang Math floor.

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:eu.matejkormuth.rpgdavid.starving.Region.java

public int getMinZFloor() {
    return (int) Math.floor(this.minVector.getZ());
}

From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java

/**
 * For r number of score levels between min and max, inclusive, this method
 * returns a r x 2 array with integer based scores in first column
 * and percentile ranks in the second column. This method is useful when
 * only the raw scores and corresponding percentile ranks are needed.
 *
 * @return two-way array of raw scores scores and percentile ranks.
 *//* w ww  .  j ava 2  s  . c o m*/
public double[][] evaluate() {
    double[][] prank = new double[freqTable.getUniqueCount()][2];
    int xstar;
    int index = 0;

    Iterator<Comparable<?>> iter = freqTable.valuesIterator();
    int x = 0;
    while (iter.hasNext()) {
        x = ((Long) iter.next()).intValue();
        xstar = Double.valueOf(Math.floor(x + 0.5)).intValue();
        prank[index][0] = xstar;
        prank[index][1] = percentileRank(x, xstar);
        index++;
        //           System.out.println("x: " + x + " xstar: " + xstar + " Fexstar: " + Fxstar + " Fxstarm1: " + Fxstarm1 + " px: " + px + " cp: " + getCummulativeProportion(xstar));
    }
    return prank;
}

From source file:dk.fambagge.recipes.web.views.RecipeView.java

public String getScaledIngredientAmountFormatted(RecipeIngredient ingredient) {
    double value = getScaledIngredientAmount(ingredient);

    String formattedValue = String.format("%.1f", value);

    if (Math.floor(value) == value) {
        formattedValue = Integer.toString((int) value);
    }/*w  w  w  . ja v  a2  s  .c  o  m*/

    boolean doFraction = true;

    if (ingredient.getMeasure() == Measure.Weight.GRAM || ingredient.getMeasure() == Measure.Weight.KILOGRAM
            || ingredient.getMeasure() == Measure.Weight.MILLIGRAM || isShowInGram()) {
        doFraction = false;
    }

    if (doFraction) {
        if (isCloseTo(value, 0.25)) {
            formattedValue = "1/4";
        } else if (isCloseTo(value, 0.5)) {
            formattedValue = "1/2";
        } else if (isCloseTo(value, 0.75)) {
            formattedValue = "3/4";
        } else if (isCloseTo(value, 0.66666666)) {
            formattedValue = "2/3";
        } else if (isCloseTo(value, 0.33333333)) {
            formattedValue = "1/3";
        }
    }

    return formattedValue;
}

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;//from   w  w w. j  a  v a 2s.co m
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:edu.oregonstate.eecs.mcplan.domains.voyager.policies.AttackPolicy.java

@Override
public VoyagerAction getAction() {
    final ArrayList<Planet> friendly_planets = Voyager.playerPlanets(s_, self_);
    final ArrayList<Planet> enemy_planets = Voyager.playerPlanets(s_, self_.enemy());
    // Consider launch actions:
    // 1. Find the closest friendly-{enemy, neutral} pair.
    //    TODO: Need to make sure it's not already targeted
    // 2. If we can safely capture from the nearest planet, do it.
    // 3. If not, transfer some Soldiers from another planet to the
    //    friendly planet.
    // 4. If all else fails, see if we would like to re-balance workers.
    if (friendly_planets.size() == 0 || enemy_planets.size() == 0) {
        return new NothingAction();
    }//from  w  w  w  .  j a  v  a  2s  . c  o  m
    double nn_strength = Voyager.defense_strength(target_.population());
    final int enemy_strength = Fn.sum(Fn.map(new Fn.IntFunction1<Planet>() {
        @Override
        public int apply(final Planet p) {
            return Voyager.defense_strength(p.population());
        }
    }, new Fn.ArraySlice<Planet>(s_.planets)));
    nn_strength += win_margin_ * enemy_strength;
    final int points_needed = Math.max((int) Math.ceil(nn_strength), 1);
    final Planet near_friendly = Voyager.nearest(target_, friendly_planets);
    final int[] nf_pop = Arrays.copyOf(near_friendly.population(), Unit.values().length);
    nf_pop[Unit.Worker.ordinal()] = (int) Math.floor(combat_worker_ratio_ * nf_pop[Unit.Worker.ordinal()]);
    final int nf_strength = Voyager.defense_strength(nf_pop);
    final int spare_workers = Math.max(0, nf_pop[Unit.Worker.ordinal()] - 1);
    final int spare_soldiers = Math.max(0, nf_pop[Unit.Soldier.ordinal()] - 1);
    // FIXME: Sending workers is pointless since they now have 0 strength.
    // Fix it better!
    final int usable_workers = 0; //Math.min( target_.capacity, spare_workers );
    final int soldiers_needed = Math.max(0, (int) Math.ceil(points_needed / (double) Unit.Soldier.attack()));
    if (spare_soldiers >= soldiers_needed) {
        final int[] launch_pop = new int[Unit.values().length];
        launch_pop[Unit.Soldier.ordinal()] = soldiers_needed;
        launch_pop[Unit.Worker.ordinal()] = usable_workers;
        return new LaunchAction(near_friendly, target_, launch_pop);
    }

    {
        // Can't take near_nonfriendly directly; reinforce near_friendly.
        final Planet n = near_friendly;
        Collections.sort(friendly_planets, new Comparator<Planet>() {
            @Override
            public int compare(final Planet a, final Planet b) {
                return (int) (Voyager.sq_distance(a, n) - Voyager.sq_distance(b, n));
            }
        });
        for (final Planet p : friendly_planets) {
            // TODO: Magic number 2
            if (p.id != near_friendly.id && p.population(Unit.Soldier) > 2) {
                final int[] launch_pop = new int[Unit.values().length];
                launch_pop[Unit.Soldier.ordinal()] = (int) Math
                        .floor(reinforce_soldier_ratio_ * p.population(Unit.Soldier));
                return new LaunchAction(p, near_friendly, launch_pop);
            }
        }
    }

    return new NothingAction();
}

From source file:com.intellectualcrafters.plot.generator.HybridPlotWorld.java

/**
 * This method is called when a world loads. Make sure you set all your constants here. You are provided with the
 * configuration section for that specific world.
 *///from w w w  .j a  v a2 s. c o  m
@Override
public void loadConfiguration(final ConfigurationSection config) {
    if (!config.contains("plot.height")) {
        PS.log(" - &cConfiguration is null? (" + config.getCurrentPath() + ")");
    }
    this.PLOT_BEDROCK = config.getBoolean("plot.bedrock");
    this.PLOT_HEIGHT = Math.min(255, config.getInt("plot.height"));
    this.PLOT_WIDTH = config.getInt("plot.size");
    this.MAIN_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST
            .parseString(StringUtils.join(config.getStringList("plot.filling"), ','));
    this.TOP_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST
            .parseString(StringUtils.join(config.getStringList("plot.floor"), ','));
    this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.block"));
    this.ROAD_WIDTH = config.getInt("road.width");
    this.ROAD_HEIGHT = Math.min(255, config.getInt("road.height"));
    this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.block"));
    this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.filling"));
    this.WALL_HEIGHT = Math.min(254, config.getInt("wall.height"));
    this.CLAIMED_WALL_BLOCK = (PlotBlock) Configuration.BLOCK
            .parseString(config.getString("wall.block_claimed"));
    this.SIZE = (short) (this.PLOT_WIDTH + this.ROAD_WIDTH);
    if ((this.ROAD_WIDTH % 2) == 0) {
        this.PATH_WIDTH_LOWER = (short) (Math.floor(this.ROAD_WIDTH / 2) - 1);
    } else {
        this.PATH_WIDTH_LOWER = (short) (Math.floor(this.ROAD_WIDTH / 2));
    }
    this.PATH_WIDTH_UPPER = (short) (this.PATH_WIDTH_LOWER + this.PLOT_WIDTH + 1);
    try {
        setupSchematics();
    } catch (final Exception e) {
        PS.log("&c - road schematics are disabled for this world.");
    }
}

From source file:eu.optimis.mi.aggregator.resources.AggregatorResource.java

@Path("/monitoringresources/{resourceType}")
@POST//from w w  w .  ja  v  a 2  s.  c o m
@Consumes(MediaType.TEXT_PLAIN)
public Response pushmonitoringResStr(String xml, @PathParam("resourceType") String resourceType)
        throws IOException {
    // Build Filename
    Date date = new Date();
    long current = (long) Math.floor(date.getTime() / 1000);
    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(10000);
    String fileName = Long.toString(current) + "-" + Integer.toString(randomInt) + ".xml";
    String filePath = null;
    if (resourceType.equals("physical")) {
        filePath = physicalPath;
    } else if (resourceType.equals("virtual"))
        filePath = virtualPath;
    else if (resourceType.equals("energy"))
        filePath = energyPath;
    else if (resourceType.equals("service"))
        filePath = servicePath;
    else
        throw new IOException();

    String filePathName = filePath + fileName;
    org.apache.commons.io.FileUtils.writeStringToFile(new File(filePathName), xml);
    return Response.ok().build();
}

From source file:org.operamasks.faces.render.graph.XYCurveAndShapeRenderer.java

/**
 * Draws the item (first pass). This method draws the lines
 * connecting the items. Instead of drawing separate lines,
 * a GeneralPath is constructed and drawn at the end of
 * the series painting.//from w  ww  . j  a va  2 s  . com
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param plot  the plot (can be used to obtain standard color information
 *              etc).
 * @param dataset  the dataset.
 * @param pass  the pass.
 * @param series  the series index (zero-based).
 * @param item  the item index (zero-based).
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataArea  the area within which the data is being drawn.
 */
protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset,
        int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) {

    if (item != 0) {
        return;
    }

    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
    PlotOrientation orientation = plot.getOrientation();

    int itemCount = dataset.getItemCount(series);
    double[][] points = new double[itemCount][2];
    int count = 0;

    for (int i = 0; i < itemCount; i++) {
        double x = dataset.getXValue(series, i);
        double y = dataset.getYValue(series, i);
        double transX = domainAxis.valueToJava2D(x, dataArea, xAxisLocation);
        double transY = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation);
        if (!Double.isNaN(transX) && !Double.isNaN(transY)) {
            points[count][0] = transX;
            points[count][1] = transY;
            count++;
        }
    }

    if (count < 2) {
        return;
    }

    // sort points according to x axis
    Arrays.sort(points, new Comparator<double[]>() {
        public int compare(double[] a, double[] b) {
            return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
        }
    });

    // draw curve
    CubicSplineFunction2D f = new CubicSplineFunction2D(points, count);
    GeneralPath path = new GeneralPath();

    double startX = points[0][0];
    double startY = points[0][1];
    double endX = points[count - 1][0];
    double endY = points[count - 1][1];
    double yz = rangeAxis.valueToJava2D(0.0, dataArea, yAxisLocation);

    if (orientation == PlotOrientation.HORIZONTAL) {
        if (drawArea) {
            path.moveTo((float) yz, (float) startX);
            path.lineTo((float) startY, (float) startX);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) f.getValue(x), (float) x);
            }
            path.lineTo((float) endY, (float) endX);
            path.lineTo((float) yz, (float) endX);
            path.closePath();
        } else {
            path.moveTo((float) startY, (float) startX);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) f.getValue(x), (float) x);
            }
            path.lineTo((float) endY, (float) endX);
        }
    } else {
        if (drawArea) {
            path.moveTo((float) startX, (float) yz);
            path.lineTo((float) startX, (float) startY);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) x, (float) f.getValue(x));
            }
            path.lineTo((float) endX, (float) endY);
            path.lineTo((float) endX, (float) yz);
            path.closePath();
        } else {
            path.moveTo((float) startX, (float) startY);
            for (double x = Math.floor(startX) + 1.0; x < endX; x += 1.0) {
                path.lineTo((float) x, (float) f.getValue(x));
            }
            path.lineTo((float) endX, (float) endY);
        }
    }

    Paint paint = getItemPaint(series, item);
    Stroke stroke = getItemStroke(series, item);

    if (drawArea) {
        g2.setPaint(paint);
        g2.fill(path);

        // create paint for outline
        if (paint instanceof Color) {
            paint = ((Color) paint).darker();
        } else if (paint instanceof GradientPaint) {
            paint = ((GradientPaint) paint).getColor1().darker();
        }
    }

    g2.setPaint(paint);
    g2.setStroke(stroke);
    g2.draw(path);
}

From source file:com.miz.mizuu.fragments.RelatedMoviesFragment.java

public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    v.findViewById(R.id.container)/*w ww  .j a va 2  s. c  o  m*/
            .setBackgroundResource(MizuuApplication.getBackgroundColorResource(getActivity()));

    MizLib.addActionBarPadding(getActivity(), v.findViewById(R.id.container));

    pbar = (ProgressBar) v.findViewById(R.id.progress);
    if (pics_sources.size() > 0)
        pbar.setVisibility(View.GONE); // Hack to remove the ProgressBar on orientation change

    mAdapter = new ImageAdapter(getActivity());

    mGridView = (GridView) v.findViewById(R.id.gridView);
    mGridView.setAdapter(mAdapter);

    // Calculate the total column width to set item heights by factor 1.5
    mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final int numColumns = (int) Math
                    .floor(mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
            if (numColumns > 0) {
                mGridView.setNumColumns(numColumns);
            }
        }
    });
    mGridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            if (movieMap.get(Integer.valueOf(pics_sources.get(arg2).getId()))) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MovieDetails.class);
                intent.putExtra("tmdbId", pics_sources.get(arg2).getId());

                // Start the Intent for result
                startActivityForResult(intent, 0);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setClass(getActivity(), TMDbMovieDetails.class);
                i.putExtra("tmdbid", pics_sources.get(arg2).getId());
                i.putExtra("title", pics_sources.get(arg2).getTitle());
                startActivity(i);
            }
        }
    });

    if (getArguments().containsKey("json")) {
        json = getArguments().getString("json");
        loadJson(getArguments().getString("baseUrl"));
    } else {
        new GetMovies().execute(getArguments().getString("tmdbId"));
    }
}