Example usage for java.lang Character getNumericValue

List of usage examples for java.lang Character getNumericValue

Introduction

In this page you can find the example usage for java.lang Character getNumericValue.

Prototype

public static int getNumericValue(int codePoint) 

Source Link

Document

Returns the int value that the specified character (Unicode code point) represents.

Usage

From source file:ivory.core.tokenize.Tokenizer.java

/**
 * Method to remove non-unicode characters from token, to prevent errors in the preprocessing pipeline. Such cases exist in German Wikipedia. 
 * /*from   w w w.ja  va2  s.  c o  m*/
 * @param token
 *    token to check for non-unicode character
 * @return
 *    token without the non-unicode characters
 */
public static String removeNonUnicodeChars(String token) {
    StringBuilder fixedToken = new StringBuilder();
    for (int i = 0; i < token.length(); i++) {
        char c = token.charAt(i);
        if (Character.getNumericValue(c) >= -1) {
            fixedToken.append(c);
        }
    }
    return fixedToken.toString();
}

From source file:io.bitsquare.gui.util.validation.AccountNrValidator.java

@Override
public ValidationResult validate(String input) {
    int length;//w ww.j a  v a2 s . c  o  m
    String input2;
    switch (countryCode) {
    case "GB":
        length = 8;
        if (isNumberWithFixedLength(input, length))
            return super.validate(input);
        else
            return new ValidationResult(false, BSResources.get("validation.accountNr", length));
    case "US":
        if (isNumberInRange(input, 4, 17))
            return super.validate(input);
        else
            return new ValidationResult(false, BSResources.get("validation.accountNr", "4 - 17"));
    case "BR":
        if (isStringInRange(input, 1, 20))
            return super.validate(input);
        else
            return new ValidationResult(false, BSResources.get("validation.accountNrChars", "1 - 20"));
    case "NZ":
        input2 = input != null ? input.replaceAll("-", "") : null;
        if (isNumberInRange(input2, 15, 16))
            return super.validate(input);
        else
            return new ValidationResult(false, "Account number must be of format: 03-1587-0050000-00");
    case "AU":
        if (isNumberInRange(input, 4, 10))
            return super.validate(input);
        else
            return new ValidationResult(false, BSResources.get("validation.accountNr", "4 - 10"));
    case "CA":
        if (isNumberInRange(input, 7, 12))
            return super.validate(input);
        else
            return new ValidationResult(false, BSResources.get("validation.accountNr", "7 - 12"));
    case "MX":
        length = 18;
        if (isNumberWithFixedLength(input, length))
            return super.validate(input);
        else
            return new ValidationResult(false,
                    BSResources.get("validation.sortCodeNumber", getLabel(), length));
    case "HK":
        input2 = input != null ? input.replaceAll("-", "") : null;
        if (isNumberInRange(input2, 9, 12))
            return super.validate(input);
        else
            return new ValidationResult(false, "Account number must be of format: 005-231289-112");
    case "NO":
        if (input != null) {
            length = 11;
            // Provided by sturles:
            // https://github.com/bitsquare/bitsquare/pull/707

            // https://no.wikipedia.org/wiki/MOD11#Implementasjoner_i_forskjellige_programmeringspr.C3.A5k
            // https://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits6

            // 11 digits, last digit is checksum.  Checksum algoritm is 
            // MOD11 with weights 2,3,4,5,6,7,2,3,4,5 right to left.
            // First remove whitespace and periods.  Normal formatting is: 
            // 1234.56.78903
            input2 = StringUtils.remove(input, " ");
            input2 = StringUtils.remove(input2, ".");
            // 11 digits, numbers only
            if (input2.length() != length || !StringUtils.isNumeric(input2))
                return new ValidationResult(false,
                        BSResources.get("validation.sortCodeNumber", getLabel(), length));
            int lastDigit = Character.getNumericValue(input2.charAt(input2.length() - 1));
            if (getMod11ControlDigit(input2) != lastDigit)
                return new ValidationResult(false, "Kontonummer har feil sjekksum");
            else
                return super.validate(input);
        } else {
            return super.validate(input);
        }
    default:
        return super.validate(input);
    }

}

From source file:org.seadpdt.people.OrcidProvider.java

/**
 * Generates check digit as per ISO 7064 11,2.
 * /*from  w w  w  . j a v a  2s  .c om*/
 */
public static boolean validCheckDigit(String id) {

    String baseDigits = id.replaceAll("-", "");
    String checkDigit = baseDigits.substring(baseDigits.length() - 1);
    baseDigits = baseDigits.substring(0, baseDigits.length() - 1);

    int total = 0;
    for (int i = 0; i < baseDigits.length(); i++) {
        int digit = Character.getNumericValue(baseDigits.charAt(i));
        total = (total + digit) * 2;
    }
    int remainder = total % 11;
    int result = (12 - remainder) % 11;
    String resultString = result == 10 ? "X" : String.valueOf(result);
    return (checkDigit.equals(resultString));

}

From source file:io.bitsquare.gui.util.validation.AccountNrValidator.java

private int getMod11ControlDigit(String accountNrString) {
    int sumForMod = 0;
    int controlNumber = 2;
    char[] accountNr = accountNrString.toCharArray();

    for (int i = accountNr.length - 2; i >= 0; i--) {
        sumForMod += (Character.getNumericValue(accountNr[i]) * controlNumber);
        controlNumber++;//  www  .  ja  va  2s  .c o m

        if (controlNumber > 7) {
            controlNumber = 2;
        }
    }
    int calculus = (11 - sumForMod % 11);
    if (calculus == 11) {
        return 0;
    } else {
        return calculus;
    }
}

From source file:com.syncedsynapse.kore2.utils.UIUtils.java

/**
 * Returns a CharacterDrawable that is suitable to use as an avatar
 * @param context Context/*from w  ww  .j  a  v  a  2 s  .  co m*/
 * @param str String to use to create the avatar
 * @return Character avatar to use in a image view
 */
public static CharacterDrawable getCharacterAvatar(Context context, String str) {
    // Load character avatar
    if (characterAvatarColors == null) {
        characterAvatarColors = context.getResources().obtainTypedArray(R.array.character_avatar_colors);
    }

    char charAvatar = TextUtils.isEmpty(str) ? ' ' : str.charAt(0);
    avatarColorsIdx = TextUtils.isEmpty(str) ? 0
            : Math.max(Character.getNumericValue(str.charAt(0))
                    + Character.getNumericValue(str.charAt(str.length() - 1)) + str.length(), 0)
                    % characterAvatarColors.length();
    int color = characterAvatarColors.getColor(avatarColorsIdx, 0xff000000);
    //            avatarColorsIdx = randomGenerator.nextInt(characterAvatarColors.length());
    return new CharacterDrawable(charAvatar, color);
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDirectoryScannerInlineFiles.java

/** Create block file and corresponding metafile in a rondom volume */
private long createInlineBlockFile(int checksumType) throws IOException {
    FSVolume[] volumes = data.volumes.getVolumes();
    int index = rand.nextInt(volumes.length - 1);
    long id = getFreeBlockId();
    File finalizedDir = volumes[index].getNamespaceSlice(nsid).getCurrentDir();
    int checksumSize = DataChecksum.getChecksumSizeByType(checksumType);
    String inlineFileName = getInlineBlockFileName(id, checksumType, checksumSize);
    File file = new File(finalizedDir, inlineFileName);
    assertTrue(file.createNewFile());// ww w  .  j a v  a  2 s  . c o  m
    PrintWriter pw = new PrintWriter(file);
    int desiredLength = (int) BlockInlineChecksumReader.getFileLengthFromBlockSize(1, 1, checksumSize);
    for (int i = 0; i < desiredLength; i++) {
        pw.write(Character.getNumericValue('0'));
    }
    pw.close();
    LOG.info("Created block file " + file.getName());
    return id;
}

From source file:com.santhoshknn.sudoku.GridExtractor.java

/**
 * <p>//from w  w  w .j  av  a  2s  .  co  m
 * Parses the supplied file to extract a 9x9 grid of integers substituting
 * the supplied x with a 0
 * </p>
 * <b>Note:</b>Used internally for testing with various data. REST API uses
 * the operation above
 *
 * @param input
 * @return extracted grid if valid input, null otherwise
 */
public GridResponse parseFromFile(final String fileName) {
    int[][] grid = new int[9][9]; // default 0 vals
    GridResponse response = new GridResponse();
    Scanner scanner = null;
    String error = null;
    try {
        URL url = getClass().getResource(fileName);
        log.info("Reading input file [{}]", url.getFile());
        scanner = new Scanner(new File(url.getPath()));
        int row = 0;
        while (scanner.hasNext()) {
            int col = 0;
            String line = scanner.nextLine();
            // delete whitespaces added for cosmetic purpose
            line = StringUtils.deleteWhitespace(line);
            if (line.isEmpty())
                continue; // Sanitize input. Remove line added for
                          // readability
                          // fail if line's length!=9
            if (line.length() != 9) {
                error = INVALID_CHARS_IN_FILE + ":" + (row + 1);
                break;
            }

            for (int i = 0; i < line.length(); i++) {
                //log.info("Row [{}] Char is [{}]",row,line.charAt(i));
                if (Character.isDigit(line.charAt(i))) {
                    int number = Character.getNumericValue(line.charAt(i));
                    grid[row][col] = number;
                } else {
                    grid[row][col] = 0;
                }
                col++;
            }
            if (row == 9)
                break;
            row++;
        }
    } catch (FileNotFoundException e) {
        log.error("Error reading file [{}]", fileName, e);
    } finally {
        if (scanner != null)
            scanner.close();
    }
    if (null == error) {
        response.setGrid(grid);
    } else {
        response.setError(error);
        log.error(error);
    }
    return response;
}

From source file:org.opensilk.video.util.Utils.java

public static int extractSeasonNumber(CharSequence title) {
    int num = -1;
    if (!StringUtils.isEmpty(title)) {
        Matcher m = TV_REGEX.matcher(title);
        if (m.matches()) {
            String episodes = m.group(2);
            if (!StringUtils.isEmpty(episodes)) {
                if (StringUtils.isNumeric(episodes)) {
                    //101 style
                    num = Character.getNumericValue(episodes.charAt(0));
                } else {
                    //s01e01 style
                    int eidx = StringUtils.indexOfAny(episodes, "Ee");
                    num = Integer.valueOf(episodes.substring(1, eidx));
                }/* w w w . j  a v  a 2 s .c  om*/
            }
        }
    }
    return num;
}

From source file:edu.osu.netmotifs.warswap.ui.GenerateMotifImages.java

public void createHtm(float zScoreCutoff, float pvalueCutoff, int recPerPage) throws Exception {
    InputStream inputStream;//from w  w w.j  a v  a2  s.  c o m
    try {
        inputStream = new FileInputStream(new File(motifsFile));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        colPerGraphHash = new HashMap<Integer, Color>();
        String headStr = "<head><style>\ntable, th, td {\nborder: 1px solid black;\nborder-collapse: collapse;\ntext-align: center;}\n</style></head>";
        String tableStr = "<table style=\"width:50%\"><tr bgcolor=\"#F1F1F1\"><th>Image</th><th>Z-score</th><th>P-Value</th><th>std-dev</th><th>Adj-Matrix</th></tr>";
        String seperator = "\t";
        if (motifsFile.endsWith("csv"))
            seperator = ",";

        line = bufferedReader.readLine();
        while ((line = bufferedReader.readLine()) != null) {
            //            Thread.sleep(1000);
            //            System.out.println(line);
            String[] parts = line.split(seperator);
            String adjMtx = parts[0];
            //String graphPart = parts[0].split("_")[1];
            Graph<Integer, String> g = new DirectedSparseGraph();
            int s = 0;
            colPerGraphHash.clear();
            for (int i = 0; i < motifSize; i++) {
                int vCode = Character.getNumericValue(adjMtx.charAt(i * (motifSize + 1)));
                colPerGraphHash.put(i, colorsHash.get(vCode));
                g.addVertex(i);
                for (int j = 0; j < motifSize; j++) {
                    int d = Character.getNumericValue(adjMtx.charAt(i * motifSize + j));
                    if (d == 1 && (i * motifSize + j) % (motifSize + 1) > 0)
                        g.addEdge("E" + s++, i, j);
                }
            }
            graphList.add(g);
            if (!parts[1].equalsIgnoreCase(CONF.INFINIT) && !parts[2].equalsIgnoreCase(CONF.INFINIT)
                    && !parts[3].equalsIgnoreCase(CONF.INFINIT)) {
                float zscore = Float.valueOf(parts[1]);
                float pValue = Float.valueOf(parts[2]);

                float stddev = Float.valueOf(parts[3]);
                //            float std = Float.valueOf(parts[3]);

                if (zScoreCutoff != -1 || pvalueCutoff != -1) {
                    if (zScoreCutoff != -1) {
                        if (zscore < zScoreCutoff)
                            continue;
                    }
                    if (pvalueCutoff != -1) {
                        if (pValue > pvalueCutoff)
                            continue;
                    }
                }
                generateImagesSize3(g, parts[0]);
                File file = new File(imageOutFile);
                tableStr += "<tr>" + "<td><img src=\"" + relativePathToImage + "\" width=\"80\" height=\"80\" >"
                        + "</td>" + "<td>" + parts[1] + "</td>" + "<td>" + parts[2] + "</td>" + "<td>"
                        + parts[3] + "</td>" + "<td>" + adjMtx + "</td>" + "</tr>";
                //               tableStr += "<tr>" + "<td><img src=\"" + imageOutFile + "\" width=\"80\" height=\"80\" >" + "</td>" 
                //                     + "<td>" + parts[1] + "</td>" + "<td>" + parts[2] + "</td>" + "<td>" + parts[3] + "</td>" + "<td>" + adjMtx + "</td>" + "</tr>";
            }
        }
        Utils.printStrToFile(headStr + tableStr, htmOutFile);
        inputStream.close();
        bufferedReader.close();
        runstatus = 1;
    } catch (Exception e) {
        e.printStackTrace();
        runstatus = 1;
        throw e;
    }
}

From source file:org.jrimum.vallia.digitoverificador.Modulo.java

/**
 * <p>/* w  w  w . j a  v  a 2 s .c  om*/
 * Realiza o clculo da soma na forma do mdulo 11.
 * </p>
 * <p>
 * O mdulo 11 funciona da seguinte maneira:
 * </p>
 * <p>
 * Cada dgito do nmero, comeando da direita para a esquerda (menos
 * significativo para o mais significativo),  multiplicado pelo nmeros
 * limite mnimo, limite mnimo + 1, limite mnimo + 2 e assim
 * sucessivamente at o limite mxmio definido, ento inicia-se novamente a
 * contagem.
 * </p>
 * <p>
 * Exemplo para o nmero <tt>654321</tt>:
 * 
 * <pre>
 * +---+---+---+---+---+---+
 * | 6 | 5 | 4 | 3 | 2 | 1 |
 * +---+---+---+---+---+---+
 *   |   |   |   |   |   |
 *  x7  x6  x5  x4  x3  x2
 *   |   |   |   |   |   |
 *  =42 =30 =20 =12 =6  =2
 *   +---+---+---+---+---+-&gt;
 * </pre
 * 
 * </p>
 * 
 * @param numero
 * @param limiteMin
 * @param limiteMax
 * @return
 * @throws IllegalArgumentException
 * 
 * @since 0.2
 */
public static int calculeSomaSequencialMod11(String numero, int limiteMin, int limiteMax)
        throws IllegalArgumentException {

    int peso = 0;
    int soma = 0;

    if (StringUtils.isNotBlank(numero) && StringUtils.isNumeric(numero)) {

        StringBuilder sb = new StringBuilder(numero);
        sb.reverse();

        peso = limiteMin;

        for (char c : sb.toString().toCharArray()) {
            soma += peso * Character.getNumericValue(c);
            peso++;

            if (peso > limiteMax)
                peso = limiteMin;
        }

    } else
        throw new IllegalArgumentException(O_ARGUMENTO_DEVE_CONTER_APENAS_NUMEROS);

    return soma;
}