예제 #1
0
 public static ArrayList<Symbol> toSymbols(String expression) {
   ArrayList<Symbol> symbols = new ArrayList<>();
   for (int i = 0; i < expression.length(); i++) {
     char c = expression.charAt(i);
     if (isBracket(c)) {
       // bracket
       symbols.add(new Symbol(c));
     } else if (c == ',') {
       symbols.add(new Symbol(c));
     } else if (isOperator(c)) {
       if (c == '-') {
         if (i == 0) {
           // must be first +/-, so add 0
           symbols.add(new Symbol(BigDecimal.valueOf(0)));
           symbols.add(new Symbol(c));
         } else {
           char previous = expression.charAt(i - 1);
           if ((previous == ')') || isNumber(String.valueOf(previous))) {
             // must be "minus"
             // e.g. sin(3)-5, 100-5,
             symbols.add(new Symbol(c));
           } else if ((previous == '(') || (previous == ',')) {
             // must be "negative"
             // e.g. (-3+5)/2
             symbols.add(new Symbol(BigDecimal.valueOf(0)));
             symbols.add(new Symbol(c));
           } else if ((previous == '*') || (previous == '/') || (previous == '^')) {
             int end = Symbol.getNumberEndAt(i + 1, expression);
             symbols.add(new Symbol(new BigDecimal(expression.substring(i, end))));
             i = end - 1;
           }
         }
       } else {
         symbols.add(new Symbol(c));
       }
     } else if (Character.isLetter(c)) {
       // function
       int end = Symbol.getFunctionEndAt(i, expression);
       symbols.add(new Symbol(expression.substring(i, end)));
       i = end - 1;
     } else if (Character.isDigit(c)) {
       int end = Symbol.getNumberEndAt(i, expression);
       String number = expression.substring(i, end);
       symbols.add(new Symbol(new BigDecimal(number)));
       i = end - 1;
     }
   }
   return symbols;
 }
예제 #2
0
 /* return string representation of fault code */
 public static String GetFaultString(long fault) {
   if (fault > 0L) {
     StringBuffer sb = new StringBuffer();
     if ((fault & TYPE_MASK) == TYPE_J1708) {
       // SID: "128/s123/1"
       // PID: "128/123/1"
       boolean active = DTOBDFault.DecodeActive(fault);
       int mid = DTOBDFault.DecodeSystem(fault);
       int fmi = DTOBDFault.DecodeFMI(fault);
       if (!active) {
         sb.append("[");
       }
       sb.append(mid); // MID
       sb.append("/");
       if (DTOBDFault.IsJ1708_SID(fault)) {
         int sid = DTOBDFault.DecodePidSid(fault);
         sb.append("s").append(sid); // SID "128/s123/1"
       } else {
         int pid = DTOBDFault.DecodePidSid(fault);
         sb.append(pid); // PID "128/123/1"
       }
       sb.append("/");
       sb.append(fmi); // FMI
       if (!active) {
         sb.append("]");
       }
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_J1939) {
       // SPN: "128/1"
       boolean active = DTOBDFault.DecodeActive(fault);
       int spn = DTOBDFault.DecodeSystem(fault);
       int fmi = DTOBDFault.DecodeFMI(fault);
       sb.append(spn); // SPN
       sb.append("/");
       sb.append(fmi); // FMI
       return sb.toString();
     } else if ((fault & TYPE_MASK) == TYPE_OBDII) {
       // DTC: "P0071" [was "024C"]
       boolean active = DTOBDFault.DecodeActive(fault);
       int sysChar = DTOBDFault.DecodeSystem(fault); // System: powertrain
       int subSys = DTOBDFault.DecodeSPID(fault); // Mfg/Subsystem/Problem
       if (Character.isLetter((char) sysChar)) {
         sb.append((char) sysChar);
       } else {
         sb.append("U");
       }
       if ((subSys & 0x8000) != 0) {
         sb.append("1");
       } else {
         sb.append("0");
       }
       String subSysStr = String.valueOf(1000 + ((subSys & 0xFFF) % 1000));
       sb.append(subSysStr.substring(1));
       return sb.toString();
     } else {
       // unrecognized
     }
   }
   return "";
 }
예제 #3
0
  /**
   * Return a set of the variables in the supplied expression. Note: Substitutions which are in the
   * constant table are not included.
   */
  public Set<String> getVariablesWithin(String exp) {
    Set<String> all = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    String add = null;

    if (separators == null) {
      StringBuilder sep = new StringBuilder(10);
      for (char chr = 0; chr < operators.length; chr++) {
        if (operators[chr] != null && !operators[chr].internal) {
          sep.append(chr);
        }
      }
      sep.append("()");
      separators = sep.toString();
    }

    for (StringTokenizer tkz = new StringTokenizer(exp, separators, true); tkz.hasMoreTokens(); ) {
      String tkn = tkz.nextToken().trim();

      if (tkn.length() != 0 && Character.isLetter(tkn.charAt(0))) {
        add = tkn;
      } else if (tkn.length() == 1 && tkn.charAt(0) == '(') {
        add = null;
      } else if (add != null && !constants.containsKey(add)) {
        all.add(add);
      }
    }
    if (add != null && !constants.containsKey(add)) {
      all.add(add);
    }
    return all;
  }
예제 #4
0
 public static boolean isFunctionName(String str) {
   /*
    * actually checks if all the chars are letters
    */
   for (char c : str.toCharArray()) {
     if (!Character.isLetter(c)) return false;
   }
   return true;
 }
예제 #5
0
 public static String modify(String in) {
   in = in.toLowerCase();
   String returnString = "";
   for (int i = 0; i < in.length(); i++) {
     char current = in.charAt(i);
     // Repeat Random Amount
     if (current == 'a' || current == 'e' || current == 'i' || current == 'o' || current == 'u') {
       if (Math.random() > 0.5) returnString += vowel[(int) Math.random() * 5];
       else returnString += Character.toUpperCase(vowel[(int) Math.random() * 5]);
     } else {
       for (int j = 0; j < (int) Math.random() * 5 + 1; j++) {
         if (Math.random() > 0.5) returnString += current;
         else returnString += Character.toUpperCase(current);
       }
     }
   }
   return returnString;
 }
예제 #6
0
 /**
  * ** Returns true if the specified character should be hex-encoded in a URL ** @param ch The
  * character to test ** @return True if the specified character should be hex-encoded in a URL
  */
 private static boolean shouldEncodeArgChar(char ch) {
   if (Character.isLetterOrDigit(ch)) {
     return false;
   } else if ((ch == '_') || (ch == '-') || (ch == '.')) {
     return false;
   } else {
     return true;
   }
 }
예제 #7
0
 private void validateName(String nam) {
   if (!Character.isLetter(nam.charAt(0))) {
     throw new IllegalArgumentException(
         "Names for constants, variables and functions must start with a letter");
   }
   if (nam.indexOf('(') != -1 || nam.indexOf(')') != -1) {
     throw new IllegalArgumentException(
         "Names for constants, variables and functions may not contain a parenthesis");
   }
 }
 public String Decrypt(String C) {
   int len = C.length() / 22;
   String M = "";
   for (int i = 0; i < len; i++) {
     String Temp = C.substring(i * 22, i * 22 + 22);
     String m = Character.toString((char) Decrypto(new BigInteger(Temp)));
     M = M.concat(m);
   }
   return M;
 }
예제 #9
0
파일: Util.java 프로젝트: protin2art/Whiley
 public static int compare(Character o1, Object o2) {
   if (o2 == null) {
     return 1;
   } else if (o2 instanceof Character) {
     Character c2 = (Character) o2;
     return o1.compareTo(c2);
   } else {
     return -1;
   }
 }
예제 #10
0
 public Field(String s) {
   String f[] = StringTools.parseString(s, FIELD_VALUE_SEPARATOR);
   if ((f.length > 0) && (f[0].length() > 0) && Character.isLetter(f[0].charAt(0))) {
     this.isHiRes = (f.length > 0) ? f[0].equalsIgnoreCase("H") : false;
     this.type = (f.length > 1) ? StringTools.parseInt(f[1], -1) : -1;
   } else {
     this.type = (f.length > 0) ? StringTools.parseInt(f[0], -1) : -1;
     this.isHiRes = (f.length > 1) ? f[1].equalsIgnoreCase("H") : false;
   }
   this.index = (f.length > 2) ? StringTools.parseInt(f[2], 0) : 0;
   this.length = (f.length > 3) ? StringTools.parseInt(f[3], 0) : 0;
   this.isValid = (f.length == 4) && (this.type >= 0) && (this.index >= 0) && (this.length > 0);
 }
예제 #11
0
  public static void main(String args[]) {

    int NUM_LETTERS = 27;
    char[] alfabet = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '?'
    };

    Scanner in = new Scanner(System.in);
    int L = in.nextInt();
    in.nextLine();
    int H = in.nextInt();
    in.nextLine();
    // to store the letter in asci artM
    char[][] art = new char[H][L * NUM_LETTERS];
    String T = in.nextLine(); // text to translate

    System.err.println("create array L:" + L + "/H:" + H + "/to translate:" + T);

    // saving asci art
    for (int i = 0; i < H; i++) {
      String ROW = in.nextLine(); // first line of all letters in asci art
      // the ROW must be saved in L chars groups
      // System.err.println("readed->" + ROW);
      char[] aux = ROW.toCharArray();
      for (int j = 0; j < aux.length; j++) {
        // System.err.println("guardando->["+i+"]["+j+"]" + aux[j]);
        art[i][j] = aux[j];
      }
    }

    StringBuilder builder = new StringBuilder();
    char[] translation = T.toCharArray();
    for (int m = 0; m < H; m++) {
      StringBuilder linea = new StringBuilder();
      for (int j = 0; j < translation.length; j++) {
        // neet to get char -> letter number to get position
        int position = returnPosition(Character.toUpperCase(translation[j]), alfabet);

        int start = (position * L);
        for (int u = start; u < (start + L); u++) {
          linea.append(art[m][u]);
        }
      }
      System.out.println(linea);
    }

    // Write an action using System.out.println()
    // To debug: System.err.println("Debug messages...");

  }
예제 #12
0
  private static boolean go(int a, int b) {
    if (memo[a][b] >= 0) return memo[a][b] == 1;

    if (a == b) return true;
    if (b - a == 1) return str[a] == ' ' || str[a] == ':' || Character.isLetter(str[a]);

    boolean ok = false;
    if (b - a == 2) ok |= str[a] == ':' && (str[a + 1] == ')' || str[a + 1] == '(');
    if (b - a >= 2 && str[a] == '(' && str[b - 1] == ')') ok |= go(a + 1, b - 1);
    for (int x = a + 1; x < b && !ok; x++) ok |= go(a, x) && go(x, b);

    memo[a][b] = ok ? 1 : 0;
    return ok;
  }
예제 #13
0
 // Find and unescape a string.
 private String readString() {
   StringBuilder sb = new StringBuilder();
   char c = next();
   if (c != '"') throw new RuntimeException("expecting start of string");
   while (true)
     switch (c = next()) {
       case '"':
         return sb.toString();
       case '\\':
         sb.append(readEscaped());
         continue;
       default:
         if (Character.isISOControl(c)) throw new RuntimeException("illegal character in string");
         sb.append(c);
     }
 }
예제 #14
0
  @Override
  public String toString() {
    switch (this.type) {
      case OPERATOR:
      case OPENING_BRACKET:
      case CLOSING_BRACKET:
        return Character.toString(operator);

      case FUNCTION:
        return this.function;

      case VALUE:
      default:
        return Arrays.toString(value);
    }
  }
예제 #15
0
 /**
  * ** Returns true if the URL starts with a protocol definition (ie. "http://...") ** @param url
  * The URL to test ** @return True if the URL starts with a protocol definition
  */
 public static boolean isAbsoluteURL(String url) {
   if (url == null) {
     return false;
   } else {
     // per "http://en.wikipedia.org/wiki/URI_scheme" all URL "schemes" contain only
     // alphanumeric or "." characters, and appears to be < 16 characters in length.
     for (int i = 0; (i < 16) && (i < url.length()); i++) {
       char ch = url.charAt(i);
       if (ch == ':') {
         return true; // A colon is the first non-alphanumeric we ran in to
       } else if (!Character.isLetterOrDigit(ch) && (ch != '.')) {
         return false;
       }
     }
     return false;
   }
 }
예제 #16
0
  private double doNamedVal(int beg, int end) {
    while (beg < end && Character.isWhitespace(expression.charAt(end))) {
      end--;
    } // since a letter triggers a named value, this can never reduce to beg==end

    String nam = expression.substring(beg, (end + 1));
    Double val;

    if ((val = constants.get(nam)) != null) {
      return val.doubleValue();
    } else if ((val = variables.get(nam)) != null) {
      isConstant = false;
      return val.doubleValue();
    } else if (relaxed) {
      isConstant = false;
      return 0.0;
    }

    throw exception(beg, "Unrecognized constant or variable \"" + nam + "\"");
  }
예제 #17
0
 // To add/remove functions change evaluateOperator() and registration
 public double evaluateFunction(String fncnam, ArgParser fncargs) throws ArithmeticException {
   switch (Character.toLowerCase(fncnam.charAt(0))) {
     case 'a':
       {
         if (fncnam.equalsIgnoreCase("abs")) {
           return Math.abs(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("acos")) {
           return Math.acos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("asin")) {
           return Math.asin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("atan")) {
           return Math.atan(fncargs.next());
         }
       }
       break;
     case 'c':
       {
         if (fncnam.equalsIgnoreCase("cbrt")) {
           return Math.cbrt(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("ceil")) {
           return Math.ceil(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cos")) {
           return Math.cos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cosh")) {
           return Math.cosh(fncargs.next());
         }
       }
       break;
     case 'e':
       {
         if (fncnam.equalsIgnoreCase("exp")) {
           return Math.exp(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("expm1")) {
           return Math.expm1(fncargs.next());
         }
       }
       break;
     case 'f':
       {
         if (fncnam.equalsIgnoreCase("floor")) {
           return Math.floor(fncargs.next());
         }
       }
       break;
     case 'g':
       {
         //              if(fncnam.equalsIgnoreCase("getExponent"   )) { return
         // Math.getExponent(fncargs.next());                } needs Java 6
       }
       break;
     case 'l':
       {
         if (fncnam.equalsIgnoreCase("log")) {
           return Math.log(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log10")) {
           return Math.log10(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log1p")) {
           return Math.log1p(fncargs.next());
         }
       }
       break;
     case 'm':
       {
         if (fncnam.equalsIgnoreCase("max")) {
           return Math.max(fncargs.next(), fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("min")) {
           return Math.min(fncargs.next(), fncargs.next());
         }
       }
       break;
     case 'n':
       {
         //              if(fncnam.equalsIgnoreCase("nextUp"        )) { return Math.nextUp
         // (fncargs.next());                } needs Java 6
       }
       break;
     case 'r':
       {
         if (fncnam.equalsIgnoreCase("random")) {
           return Math.random();
         } // impure
         if (fncnam.equalsIgnoreCase("round")) {
           return Math.round(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("roundHE")) {
           return Math.rint(fncargs.next());
         } // round half-even
       }
       break;
     case 's':
       {
         if (fncnam.equalsIgnoreCase("signum")) {
           return Math.signum(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sin")) {
           return Math.sin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sinh")) {
           return Math.sinh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sqrt")) {
           return Math.sqrt(fncargs.next());
         }
       }
       break;
     case 't':
       {
         if (fncnam.equalsIgnoreCase("tan")) {
           return Math.tan(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("tanh")) {
           return Math.tanh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toDegrees")) {
           return Math.toDegrees(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toRadians")) {
           return Math.toRadians(fncargs.next());
         }
       }
       break;
     case 'u':
       {
         if (fncnam.equalsIgnoreCase("ulp")) {
           return Math.ulp(fncargs.next());
         }
       }
       break;
       // no default
   }
   throw new UnsupportedOperationException(
       "MathEval internal function setup is incorrect - internal function \""
           + fncnam
           + "\" not handled");
 }
예제 #18
0
 private int skipWhitespace(String exp, int ofs, int end) {
   while (ofs <= end && Character.isWhitespace(exp.charAt(ofs))) {
     ofs++;
   }
   return ofs;
 }
예제 #19
0
  /**
   * Evaluate the next operand of an expression.
   *
   * @param beg Inclusive begin offset for subexpression.
   * @param end Inclusive end offset for subexpression.
   * @param pnd Pending operator (operator previous to this subexpression).
   * @param lft Left-value with which to initialize this subexpression.
   * @param cur Current operator (the operator for this subexpression).
   */
  private double _evaluate(int beg, int end, double lft, Operator pnd, Operator cur)
      throws NumberFormatException, ArithmeticException {
    Operator nxt = OPERAND; // next operator
    int ofs; // current expression offset

    for (ofs = beg; (ofs = skipWhitespace(expression, ofs, end)) <= end; ofs++) {
      boolean fnc = false;
      double rgt = Double.NaN; // next operand (right-value) to process

      for (beg = ofs; ofs <= end; ofs++) {
        char chr = expression.charAt(ofs);
        if ((nxt = getOperator(chr)) != OPERAND) {
          if (nxt.internal) {
            nxt = OPERAND;
          } // must kill operator to prevent spurious "Expression ends with a blank sub-expression"
            // at end of function
          else {
            break;
          }
        } else if (chr == ')' || chr == ',') { // end of subexpression or function argument.
          break;
        }
      }

      EvaluateOperand:
      {
        char ch0 = expression.charAt(beg);
        boolean alp = Character.isLetter(ch0);

        if (cur.unary != LEFT_SIDE) {
          if (ch0 == '+') {
            continue;
          } // unary '+': no-op; i.e. +(-1) == -1
          if (ch0 == '-') {
            nxt = getOperator('±');
          } // unary '-': right-binding, high precedence operation (different from subtract)
        }

        if (beg == ofs && (cur.unary == LEFT_SIDE || nxt.unary == RIGHT_SIDE)) {
          rgt =
              Double
                  .NaN; // left-binding unary operator; right value will not be used and should be
                        // blank
        } else if (ch0 == '(') {
          rgt = _evaluate(beg + 1, end);
          ofs =
              skipWhitespace(
                  expression, offset + 1, end); // skip past ')' and any following whitespace
          nxt =
              (ofs <= end ? getOperator(expression.charAt(ofs)) : OPERAND); // modify next operator
        } else if (alp && nxt.symbol == '(') {
          rgt = doFunction(beg, end);
          ofs =
              skipWhitespace(
                  expression, offset + 1, end); // skip past ')' and any following whitespace
          nxt =
              (ofs <= end ? getOperator(expression.charAt(ofs)) : OPERAND); // modify next operator
        } else if (alp) {
          rgt = doNamedVal(beg, (ofs - 1));
        } else {
          try {
            if (stringOfsEq(expression, beg, "0x")) {
              rgt = (double) Long.parseLong(expression.substring(beg + 2, ofs).trim(), 16);
            } else {
              rgt = Double.parseDouble(expression.substring(beg, ofs).trim());
            }
          } catch (NumberFormatException thr) {
            throw exception(
                beg, "Invalid numeric value \"" + expression.substring(beg, ofs).trim() + "\"");
          }
        }
      }

      if (opPrecedence(cur, LEFT_SIDE)
          < opPrecedence(
              nxt,
              RIGHT_SIDE)) { // correct even for last (non-operator) character, since non-operators
                             // have the artificial "precedence" zero
        rgt =
            _evaluate(
                (ofs + 1), end, rgt, cur,
                nxt); // from after operator to end of current subexpression
        ofs = offset; // modify offset to after subexpression
        nxt = (ofs <= end ? getOperator(expression.charAt(ofs)) : OPERAND); // modify next operator
      }

      lft = doOperation(beg, lft, cur, rgt);

      cur = nxt;
      if (opPrecedence(pnd, LEFT_SIDE) >= opPrecedence(cur, RIGHT_SIDE)) {
        break;
      }
      if (cur.symbol == '(') {
        ofs--;
      } // operator omitted for implicit multiplication of subexpression
    }
    if (ofs > end && cur != OPERAND) {
      if (cur.unary == LEFT_SIDE) {
        lft = doOperation(beg, lft, cur, Double.NaN);
      } else {
        throw exception(
            ofs, "Expression ends with a blank operand after operator '" + nxt.symbol + "'");
      }
    }
    offset = ofs;
    return lft;
  }