Example usage for java.lang Double intValue

List of usage examples for java.lang Double intValue

Introduction

In this page you can find the example usage for java.lang Double intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Double as an int after a narrowing primitive conversion.

Usage

From source file:com.turt2live.xmail.mail.attachment.ItemAttachment.java

@SuppressWarnings("unchecked")
public static ItemAttachment deserializeFromJson(String content) {
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory = new ContainerFactory() {
        @Override//from   w  ww  .j a  v a2  s  . c om
        public List<Object> creatArrayContainer() {
            return new LinkedList<Object>();
        }

        @Override
        public Map<String, Object> createObjectContainer() {
            return new LinkedHashMap<String, Object>();
        }

    };

    Map<String, Object> keys = new HashMap<String, Object>();

    try {
        Map<?, ?> json = (Map<?, ?>) parser.parse(content, containerFactory);
        Iterator<?> iter = json.entrySet().iterator();

        // Type check
        while (iter.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) iter.next();
            if (!(entry.getKey() instanceof String)) {
                throw new IllegalArgumentException("Not in <String, Object> format");
            }
        }

        keys = (Map<String, Object>) json;
    } catch (ParseException e) {
        e.printStackTrace();
        return new ItemAttachment(new ItemStack(Material.GRASS, 1));
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return new ItemAttachment(new ItemStack(Material.GRASS, 1));
    }

    // Repair Gson thinking int == double
    if (keys.get("amount") != null) {
        Double d = (Double) keys.get("amount");
        Integer i = d.intValue();
        keys.put("amount", i);
    }

    ItemStack item = null;
    try {
        item = ItemStack.deserialize(keys);
    } catch (Exception e) {
        return null;
    }

    // Handle item meta
    if (keys.containsKey("meta")) {
        Map<String, Object> itemmeta = (Map<String, Object>) keys.get("meta");
        // Convert doubles -> ints
        itemmeta = recursiveDoubleToInteger(itemmeta);

        // Deserilize everything
        itemmeta = recursiveDeserialization(itemmeta);

        // Create the Item Meta
        ItemMeta meta = (ItemMeta) ConfigurationSerialization.deserializeObject(itemmeta,
                ConfigurationSerialization.getClassByAlias("ItemMeta"));

        // Colorize everything
        if (meta.hasDisplayName()) {
            meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', meta.getDisplayName()));
        }
        if (meta.hasLore()) {
            List<String> lore = meta.getLore();
            for (int i = 0; i < lore.size(); i++) {
                String line = lore.get(i);
                line = ChatColor.translateAlternateColorCodes('?', line);
                line = ChatColor.translateAlternateColorCodes('&', line);
                lore.set(i, line);
            }
            meta.setLore(lore);
        }
        if (meta instanceof BookMeta) {
            BookMeta book = (BookMeta) meta;
            if (book.hasAuthor()) {
                book.setAuthor(ChatColor.translateAlternateColorCodes('&', book.getAuthor()));
            }
            if (book.hasTitle()) {
                book.setTitle(ChatColor.translateAlternateColorCodes('&', book.getTitle()));
            }
            if (book.hasPages()) {
                List<String> pages = new ArrayList<String>();
                pages.addAll(book.getPages());
                for (int i = 0; i < pages.size(); i++) {
                    String line = pages.get(i);
                    line = ChatColor.translateAlternateColorCodes('&', line);
                    pages.set(i, line);
                }
                book.setPages(pages);
            }
        }

        // Assign the item meta
        item.setItemMeta(meta);
    }
    return new ItemAttachment(item);
}

From source file:spade.transformer.Aggregation.java

private static String applyFunctionOnList(List<String> list, String function) {
    if (function.equals("unique")) {
        Set<String> set = new HashSet<>(list);
        list = new ArrayList<>(set);
        sortList_StringAsDouble(list);/*ww w  .  j av a  2s  . c o m*/

        return list.toString();
    } else {
        sortList_StringAsDouble(list);
        if (function.equals("list")) {
            return list.toString();
        } else if (function.equals("minmax")) {
            if (list.size() > 0) {
                return "[" + list.get(0) + ", " + list.get(list.size() - 1) + "]";
            } else {
                return "[]";
            }
        } else if (function.equals("sum")) {
            Double sum = 0.0;
            for (String string : list) {
                sum += parseDouble(string);
            }
            String sumString = sum.toString();
            if (sum == sum.intValue()) {
                sumString = String.valueOf(sum.intValue());
            }
            return "[" + sumString + "]";
        } else if (function.equals("count")) {
            return "[" + list.size() + "]";
        }
    }

    return "[unknown_aggregation_function:" + function + "]";
}

From source file:de.tudarmstadt.ukp.dkpro.tc.weka.report.WekaOutcomeIDUsingTCEvaluationReport.java

protected static Properties generateProperties(Instances predictions, boolean isMultiLabel,
        boolean isRegression, List<String> labels, File mlResults) throws ClassNotFoundException, IOException {
    Properties props = new Properties();
    String[] classValues = new String[predictions.numClasses()];

    for (int i = 0; i < predictions.numClasses(); i++) {
        classValues[i] = predictions.classAttribute().value(i);
    }//from w  w  w.j  a  v a  2s  . co  m

    int attOffset = predictions.attribute(Constants.ID_FEATURE_NAME).index();

    if (isMultiLabel) {
        Map<String, Integer> class2number = Id2Outcome.classNamesToMapping(labels);
        MultilabelResult r = WekaUtils.readMlResultFromFile(mlResults);
        int[][] goldmatrix = r.getGoldstandard();
        double[][] predictionsmatrix = r.getPredictions();
        double bipartition = r.getBipartitionThreshold();

        for (int i = 0; i < goldmatrix.length; i++) {
            Double[] predList = new Double[labels.size()];
            Integer[] goldList = new Integer[labels.size()];
            for (int j = 0; j < goldmatrix[i].length; j++) {
                int classNo = class2number.get(labels.get(j));
                goldList[classNo] = goldmatrix[i][j];
                predList[classNo] = predictionsmatrix[i][j];
            }
            String s = (StringUtils.join(predList, ",") + SEPARATOR_CHAR + StringUtils.join(goldList, ",")
                    + SEPARATOR_CHAR + bipartition);
            props.setProperty(predictions.get(i).stringValue(attOffset), s);
        }
    }
    // single-label
    else {
        for (Instance inst : predictions) {
            Double gold;
            try {
                gold = new Double(inst.value(predictions
                        .attribute(Constants.CLASS_ATTRIBUTE_NAME + WekaUtils.COMPATIBLE_OUTCOME_CLASS)));
            } catch (NullPointerException e) {
                // if train and test data have not been balanced
                gold = new Double(inst.value(predictions.attribute(Constants.CLASS_ATTRIBUTE_NAME)));
            }
            Attribute gsAtt = predictions.attribute(WekaTestTask.PREDICTION_CLASS_LABEL_NAME);
            Double prediction = new Double(inst.value(gsAtt));
            if (!isRegression) {
                Map<String, Integer> class2number = Id2Outcome.classNamesToMapping(labels);
                Integer predictionAsNumber = class2number.get(gsAtt.value(prediction.intValue()));
                Integer goldAsNumber = class2number.get(classValues[gold.intValue()]);
                props.setProperty(inst.stringValue(attOffset), predictionAsNumber + SEPARATOR_CHAR
                        + goldAsNumber + SEPARATOR_CHAR + String.valueOf(-1));
            } else {
                // the outcome is numeric
                props.setProperty(inst.stringValue(attOffset),
                        prediction + SEPARATOR_CHAR + gold + SEPARATOR_CHAR + String.valueOf(0));
            }
        }
    }
    return props;
}

From source file:org.sonar.java.checks.verifier.CheckVerifier.java

private static void validateAnalyzerMessage(Map<IssueAttribute, String> attrs,
        AnalyzerMessage analyzerMessage) {
    Double effortToFix = analyzerMessage.getCost();
    if (effortToFix != null) {
        assertEquals(Integer.toString(effortToFix.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX);
    }//  w w w  .j  av a2  s  .  c o m
    AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation();
    assertEquals(normalizeColumn(textSpan.startCharacter), attrs, IssueAttribute.START_COLUMN);
    assertEquals(Integer.toString(textSpan.endLine), attrs, IssueAttribute.END_LINE);
    assertEquals(normalizeColumn(textSpan.endCharacter), attrs, IssueAttribute.END_COLUMN);
    if (attrs.containsKey(IssueAttribute.SECONDARY_LOCATIONS)) {
        List<AnalyzerMessage> secondaryLocations = analyzerMessage.flows.stream().map(l -> l.get(0))
                .collect(Collectors.toList());
        Multiset<String> actualLines = HashMultiset.create();
        for (AnalyzerMessage secondaryLocation : secondaryLocations) {
            actualLines.add(Integer.toString(secondaryLocation.getLine()));
        }
        List<String> expected = Lists.newArrayList(Splitter.on(",").omitEmptyStrings().trimResults()
                .split(attrs.get(IssueAttribute.SECONDARY_LOCATIONS)));
        List<String> unexpected = new ArrayList<>();
        for (String actualLine : actualLines) {
            if (expected.contains(actualLine)) {
                expected.remove(actualLine);
            } else {
                unexpected.add(actualLine);
            }
        }
        if (!expected.isEmpty() || !unexpected.isEmpty()) {
            // Line is not covered by JaCoCo because of thrown exception but effectively covered in UT.
            Fail.fail(String.format("Secondary locations: expected: %s unexpected:%s. In %s:%d", expected,
                    unexpected, normalizedFilePath(analyzerMessage), analyzerMessage.getLine()));
        }
    }
}

From source file:org.apache.pig.impl.util.CastUtils.java

public static Integer stringToInteger(String str) {
    if (str == null) {
        return null;
    } else {// w w w  .  j a v a  2 s.  com
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            // It's possible that this field can be interpreted as a double.
            // Unfortunately Java doesn't handle this in Integer.valueOf. So
            // we need to try to convert it to a double and if that works
            // then
            // go to an int.
            try {
                Double d = Double.valueOf(str);
                // Need to check for an overflow error
                if (d.doubleValue() > mMaxInt.doubleValue() + 1.0) {
                    LogUtils.warn(CastUtils.class, "Value " + d + " too large for integer",
                            PigWarning.TOO_LARGE_FOR_INT, mLog);
                    return null;
                }
                return Integer.valueOf(d.intValue());
            } catch (NumberFormatException nfe2) {
                LogUtils.warn(CastUtils.class,
                        "Unable to interpret value " + str + " in field being "
                                + "converted to int, caught NumberFormatException <" + e.getMessage()
                                + "> field discarded",
                        PigWarning.FIELD_DISCARDED_TYPE_CONVERSION_FAILED, mLog);
                return null;
            }
        }
    }
}

From source file:org.sonar.java.checks.verifier.CheckVerifier.java

private static void validateIssue(Multimap<Integer, Map<IssueAttribute, String>> expected,
        List<Integer> unexpectedLines, AnalyzerMessage issue,
        @Nullable RemediationFunction remediationFunction) {
    int line = issue.getLine();
    if (expected.containsKey(line)) {
        Map<IssueAttribute, String> attrs = Iterables.getLast(expected.get(line));
        assertEquals(issue.getMessage(), attrs, IssueAttribute.MESSAGE);
        Double cost = issue.getCost();
        if (cost != null) {
            Preconditions.checkState(remediationFunction != RemediationFunction.CONST,
                    "Rule with constant remediation function shall not provide cost");
            assertEquals(Integer.toString(cost.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX);
        } else if (remediationFunction == RemediationFunction.LINEAR) {
            Fail.fail("A cost should be provided for a rule with linear remediation function");
        }//from  ww  w.  ja  v  a 2 s.  c  om
        validateAnalyzerMessage(attrs, issue);
        expected.remove(line, attrs);
    } else {
        unexpectedLines.add(line);
    }
}

From source file:com.github.jessemull.microflex.util.DoubleUtil.java

/**
 * Converts a list of doubles to a list of integers.
 * @param    List<Double>    list of doubles
 * @return                   list of shorts
 *//*  w  w  w .  j a v  a 2  s . c om*/
public static List<Integer> toIntList(List<Double> list) {

    List<Integer> intList = new ArrayList<Integer>();

    for (Double val : list) {
        if (!OverFlowUtil.intOverflow(val)) {
            OverFlowUtil.overflowError(val);
        }
        intList.add(val.intValue());
    }

    return intList;

}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean isDigit(String str) {
    if (str == null || str.trim().equals("")) {
        return false;
    }//from w w w  . j a  va2  s  .  c  om
    Double val = null;
    try {
        val = Double.parseDouble(str);
    } catch (Exception e) {
        return false;
    }
    String tempStr = val.intValue() + "";
    boolean isDigit = tempStr.matches("\\d+");
    return isDigit;
}

From source file:com.lm.lic.manager.util.GenUtil.java

public static Integer calculateNumLicenses(Double payment, Double ppl) {
    payment *= 100; // make in pennies since price of licenses is in pennies
    Double numLics = payment / ppl;
    if (payment % ppl > 0) // generous
        numLics += 1;/*from   www . j a  v a2 s.c  o  m*/
    Integer nl = numLics.intValue();
    return nl;
}

From source file:utils.LocoUtils.java

public static Integer stringToInteger(String str) {
    if (str == null) {
        return null;
    } else {/*from  www. j  a  va2 s. c  o m*/
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            // It's possible that this field can be interpreted as a double.
            // Unfortunately Java doesn't handle this in Integer.valueOf. So
            // we need to try to convert it to a double and if that works
            // then
            // go to an int.
            try {
                Double d = Double.valueOf(str);
                // Need to check for an overflow error
                if (d.doubleValue() > mMaxInt.doubleValue() + 1.0) {
                    Logger.warn(TAG + "|Value " + d + " too large for integer");
                    return null;
                }
                return Integer.valueOf(d.intValue());
            } catch (NumberFormatException nfe2) {
                Logger.warn(TAG + "|Unable to interpret value " + str + " in field being "
                        + "converted to int, caught NumberFormatException <" + e.getMessage()
                        + "> field discarded");
                return null;
            }
        }
    }
}