/** remove leading spaces */
  public static final String stripSpaces(final String data) {
    final StringBuilder text = new StringBuilder((data));

    // strip leading chars
    while (text.length() > 0) {
      if (text.charAt(0) != ' ') {
        break;
      }
      text.deleteCharAt(0);

      // strip ending chars
      int pointer2 = text.length() - 1;
      while (pointer2 > 0) {
        if (text.charAt(pointer2) != ' ') {
          break;
        }
        text.deleteCharAt(pointer2);
        pointer2--;
        if (pointer2 < 0) {
          break;
        }
      }
    }
    return text.toString();
  }
Example #2
1
File: B.java Project: hiuchida/exam
 void solve() {
   int n = readNum();
   int[] num = readNums();
   int[] a = new int[n];
   int[] b = new int[n];
   int[] r = new int[n];
   for (int i = 1; i <= n; i++) {
     r[num[i - 1] - 1] = i;
   }
   for (int i = 1; i <= n; i++) {
     a[i - 1] = 30000 * i;
     b[i - 1] = 30000 * (n - i + 1) + r[i - 1];
   }
   for (int i = 0; i < n; i++) {
     sb.append(a[i]).append(" ");
   }
   sb.deleteCharAt(sb.length() - 1);
   pln(sb.toString());
   sb.delete(0, sb.length());
   for (int i = 0; i < n; i++) {
     sb.append(b[i]).append(" ");
   }
   sb.deleteCharAt(sb.length() - 1);
   pln(sb.toString());
 }
Example #3
1
  /**
   * List the entities in JSON format
   *
   * @param entities entities to return as JSON strings
   */
  public static String writeJSON(Iterable<Entity> entities) {
    logger.log(Level.INFO, "creating JSON format object");
    StringBuilder sb = new StringBuilder();

    int i = 0;
    sb.append("{\"data\": [");
    for (Entity result : entities) {
      Map<String, Object> properties = result.getProperties();
      sb.append("{");
      if (result.getKey().getName() == null)
        sb.append("\"name\" : \"" + result.getKey().getId() + "\",");
      else sb.append("\"name\" : \"" + result.getKey().getName() + "\",");

      for (String key : properties.keySet()) {
        Object object = properties.get(key);
        if (object instanceof Text) {
          Text value = (Text) properties.get(key);
          sb.append("\"" + key + "\" : \"" + value.getValue() + "\",");
          // logger.info(value.getValue());//debug;
        } else {
          sb.append("\"" + key + "\" : \"" + properties.get(key) + "\",");
        }
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("},");
      i++;
    }
    if (i > 0) {
      sb.deleteCharAt(sb.lastIndexOf(","));
    }
    sb.append("]}");
    return sb.toString();
  }
Example #4
1
  private static String fourDigits2Chinese(String digit) {

    int value = Integer.parseInt(digit);
    boolean hasZero = false;

    StringBuilder chineseDigit = new StringBuilder();

    int exponent = 3;
    for (; exponent >= 0; exponent--) {

      int divisor = (int) Math.pow(10, exponent);
      int result = value / divisor;
      if (result != 0) {
        chineseDigit.append(TOBIG[result]);
        chineseDigit.append(FOUR_DIGIT_UNIT[exponent]);
        hasZero = false;
      } else if (result == 0 && !hasZero) {
        chineseDigit.append(TOBIG[0]);
        hasZero = true;
      }
      value %= divisor;
    }

    // Delete redundant zero at head
    if (chineseDigit.toString().startsWith("零")) {
      chineseDigit.deleteCharAt(0);
    }

    // Delete redundant zero at tail
    if (chineseDigit.toString().endsWith("零")) {
      return chineseDigit.deleteCharAt(chineseDigit.length() - 1).toString();
    } else {
      return chineseDigit.toString();
    }
  }
Example #5
1
  static Integer helper(int i, StringBuilder sb, String s) {
    if (i == s.length()) {
      return decode(sb.toString());
    }

    if (!Character.isLetter(s.charAt(i))) {
      sb.append(s.charAt(i));
      Integer result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
    } else {
      char ch = s.charAt(i);
      sb.append(Character.toUpperCase(ch));
      Integer result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
      sb.deleteCharAt(sb.length() - 1);

      sb.append(Character.toLowerCase(ch));
      result = helper(i + 1, sb, s);
      if (result != null) {
        return result;
      }
      sb.deleteCharAt(sb.length() - 1);
    }
    return null;
  }
Example #6
1
  // build query
  @Override
  protected String buildQueryUrl(RequestParams params) {
    String uri = params.getUri();
    StringBuilder queryBuilder = new StringBuilder(uri);
    if (!uri.contains("?")) {
      queryBuilder.append("?");
    } else if (!uri.endsWith("?")) {
      queryBuilder.append("&");
    }
    HashMap<String, String> queryParams = params.getQueryStringParams();
    if (queryParams != null) {
      for (Map.Entry<String, String> entry : queryParams.entrySet()) {
        String name = entry.getKey();
        String value = entry.getValue();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
          queryBuilder.append(Uri.encode(name)).append("=").append(Uri.encode(value)).append("&");
        }
      }
      if (queryBuilder.charAt(queryBuilder.length() - 1) == '&') {
        queryBuilder.deleteCharAt(queryBuilder.length() - 1);
      }
    }

    if (queryBuilder.charAt(queryBuilder.length() - 1) == '?') {
      queryBuilder.deleteCharAt(queryBuilder.length() - 1);
    }
    return queryBuilder.toString();
  }
Example #7
1
  private void addUsernameCookie(
      String username,
      String firstname,
      String lastname,
      HttpServletRequest request,
      HttpServletResponse response) {
    StringBuilder un = new StringBuilder(new String(Base64.encodeBase64(username.getBytes())));
    while (un.charAt(un.length() - 1) == '=') {
      un.deleteCharAt(un.length() - 1);
    }
    response.addCookie(createCookie(USERNAME, un.toString(), request));

    StringBuilder fn = new StringBuilder();
    if (!StringUtils.isBlank(firstname)) {
      fn.append(firstname);
    }
    fn.append(":");
    if (!StringUtils.isBlank(lastname)) {
      fn.append(lastname);
    }
    String value = fn.toString();
    fn = new StringBuilder(new String(Base64.encodeBase64(value.getBytes())));
    while (fn.charAt(fn.length() - 1) == '=') {
      fn.deleteCharAt(fn.length() - 1);
    }
    Cookie c = createCookie(FULLNAME, fn.toString(), request);
    c.setMaxAge(Integer.MAX_VALUE);
    response.addCookie(c);
  }
Example #8
1
 /**
  * Trim leading and trailing whitespace from the given String.
  *
  * @param str the String to check
  * @return the trimmed String
  * @see Character#isWhitespace
  */
 public static String trimWhitespace(String str) {
   if (!hasLength(str)) {
     return str;
   }
   StringBuilder sb = new StringBuilder(str);
   while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
     sb.deleteCharAt(0);
   }
   while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
     sb.deleteCharAt(sb.length() - 1);
   }
   return sb.toString();
 }
Example #9
1
 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
     throws BadLocationException {
   StringBuilder builder = new StringBuilder(string);
   for (int i = builder.length() - 1; i >= 0; i--) {
     int cp = builder.codePointAt(i);
     if (!Character.isDigit(cp) && cp != '-') {
       builder.deleteCharAt(i);
       if (Character.isSupplementaryCodePoint(cp)) {
         i--;
         builder.deleteCharAt(i);
       }
     }
   }
   super.insertString(fb, offset, builder.toString(), attr);
 }
 /**
  * Append a time to the string builder.
  *
  * @param buff the target string builder
  * @param nanos the time in nanoseconds
  * @param alwaysAddMillis whether to always add at least ".0"
  */
 static void appendTime(StringBuilder buff, long nanos, boolean alwaysAddMillis) {
   if (nanos < 0) {
     buff.append('-');
     nanos = -nanos;
   }
   long ms = nanos / 1000000;
   nanos -= ms * 1000000;
   long s = ms / 1000;
   ms -= s * 1000;
   long m = s / 60;
   s -= m * 60;
   long h = m / 60;
   m -= h * 60;
   StringUtils.appendZeroPadded(buff, 2, h);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, m);
   buff.append(':');
   StringUtils.appendZeroPadded(buff, 2, s);
   if (alwaysAddMillis || ms > 0 || nanos > 0) {
     buff.append('.');
     int start = buff.length();
     StringUtils.appendZeroPadded(buff, 3, ms);
     if (nanos > 0) {
       StringUtils.appendZeroPadded(buff, 6, nanos);
     }
     for (int i = buff.length() - 1; i > start; i--) {
       if (buff.charAt(i) != '0') {
         break;
       }
       buff.deleteCharAt(i);
     }
   }
 }
  public static String discloseString(String string) {
    StringBuilder sb = new StringBuilder(string);

    sb.deleteCharAt(0);
    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
  }
Example #12
0
 /**
  * 使用或预览当前选中的符号或编号方式
  *
  * @param isView 是否为预览模式,当为true时表示为预览当前模式,否则为使用当前模式
  */
 private void signIdentifier(boolean isView) {
   String[] arrText = null;
   if (isView) {
     arrText = Util.SIGN_CHARS_VIEW.split("\n");
   } else {
     arrText = Util.getCurrentLinesArray(this.txaSource);
   }
   if (arrText == null || arrText.length < 1) {
     return;
   }
   boolean isSpecial = false;
   if (this.tpnMain.getTitleAt(this.tpnMain.getSelectedIndex()).equals("编号")) {
     isSpecial = true;
   }
   this.toConvertArray(arrText, isSpecial);
   StringBuilder stbIndent = new StringBuilder();
   for (String str : arrText) {
     stbIndent.append(str + "\n");
   }
   if (isView) {
     this.txaView.setText(
         stbIndent.deleteCharAt(stbIndent.length() - 1).toString()); // 删除字符串末尾多余的换行符
   } else {
     this.txaSource.replaceSelection(
         stbIndent.deleteCharAt(stbIndent.length() - 1).toString()); // 删除字符串末尾多余的换行符
   }
 }
Example #13
0
 private static void trim(StringBuilder s) {
   // remove leading line breaks
   while (s.length() > 0 && (s.charAt(0) == '\n' || s.charAt(0) == '\r')) s.deleteCharAt(0);
   // remove trailing line breaks
   while (s.length() > 0 && (s.charAt(s.length() - 1) == '\n' || s.charAt(s.length() - 1) == '\r'))
     s.deleteCharAt(s.length() - 1);
 }
 /**
  * Creates a new hexadecimal string object so that it represents the same sequence of character
  * data specified by the argument. This constructor should only be used in the context of the
  * parser which has leading and ending angled brackets which are removed by this method.
  *
  * @param stringBuffer the initial contents of the hexadecimal string object
  */
 public HexStringObject(StringBuilder stringBuffer) {
   // remove angled brackets, passed in by parser
   stringBuffer.deleteCharAt(0);
   stringBuffer.deleteCharAt(stringBuffer.length() - 1);
   // append string data
   stringData = new StringBuilder(stringBuffer.length());
   stringData.append(normalizeHex(stringBuffer, 2).toString());
 }
 @Override
 public InputStream getInputStream() throws IOException {
   if (inputStream == null) {
     outClosed = true;
     JsonArray users =
         new JsonParser()
             .parse(new String(outputStream.toByteArray(), Charsets.UTF_8))
             .getAsJsonArray();
     StringBuilder reply = new StringBuilder("[");
     StringBuilder missingUsers = new StringBuilder("[");
     for (JsonElement user : users) {
       String username = user.getAsString().toLowerCase();
       String info = cache.getIfPresent(username);
       if (info != null) {
         reply.append(info).append(",");
       } else {
         missingUsers.append("\"").append(username).append("\"").append(",");
       }
     }
     if (missingUsers.length() > 1) {
       missingUsers.deleteCharAt(missingUsers.length() - 1).append("]");
     }
     if (missingUsers.length() > 2) {
       HttpURLConnection connection;
       if (proxy == null) {
         connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url);
       } else {
         connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url, proxy);
       }
       connection.setRequestMethod("POST");
       connection.setRequestProperty("Content-Type", "application/json");
       connection.setDoInput(true);
       connection.setDoOutput(true);
       OutputStream out = connection.getOutputStream();
       out.write(missingUsers.toString().getBytes(Charsets.UTF_8));
       out.flush();
       out.close();
       JsonArray newUsers =
           new JsonParser()
               .parse(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))
               .getAsJsonArray();
       for (JsonElement user : newUsers) {
         JsonObject u = user.getAsJsonObject();
         cache.put(u.get("name").getAsString(), u.toString());
         reply.append(u.toString()).append(",");
       }
       responseCode = connection.getResponseCode();
       errorStream = connection.getErrorStream();
     } else {
       responseCode = HTTP_OK;
     }
     if (reply.length() > 1) {
       reply.deleteCharAt(reply.length() - 1);
     }
     inputStream = new ByteArrayInputStream(reply.append("]").toString().getBytes(Charsets.UTF_8));
   }
   return inputStream;
 }
Example #16
0
  /*
  CREATE TABLE `student_info` (
  `stu_name` varchar(255) DEFAULT NULL,
  `stu_age` int(11) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_score` double(10,4) DEFAULT NULL,
  `stu_date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
  ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
  */
  public static String[] parseCreateTableStat(String sql) {

    String[] parseTableInfo = new String[3];

    String[] splitLine = sql.split("\n");

    // 解析表名
    if (splitLine[0].contains("CREATE TABLE")) {

      Pattern pattern = Pattern.compile("`(.*)`");
      Matcher matcher = pattern.matcher(splitLine[0]);

      if (matcher.find()) {
        String tableName = matcher.group(1);
        LOGGER.info("Table Name : " + tableName);
        parseTableInfo[0] = tableName;
      }
    } else {
      try {
        throw new Exception("sql statements error!!!");
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }

    // 解析字段名和字段类型
    StringBuilder colNameStr = new StringBuilder();
    StringBuilder colTypeStr = new StringBuilder();
    for (int i = 1; i < splitLine.length; i++) {

      if (splitLine[i].contains("AUTO_INCREMENT")) {
        continue;
      }
      if (splitLine[i].contains("PRIMARY KEY")) {
        break;
      }
      Pattern pattern = Pattern.compile("`(.*)` ([a-z]{1,})");
      Matcher matcher = pattern.matcher(splitLine[i]);
      if (matcher.find()) {
        String colName = matcher.group(1);
        String colType = matcher.group(2);
        LOGGER.info("colName:" + colName + ",colType:" + colType);
        colNameStr.append(colName).append(",");
        colTypeStr.append(colType).append(",");
      }
    }

    colNameStr.deleteCharAt(colNameStr.length() - 1);
    colTypeStr.deleteCharAt(colTypeStr.length() - 1);
    LOGGER.info("colNameStr:" + colNameStr);
    LOGGER.info("colTypeStr:" + colTypeStr);
    parseTableInfo[1] = colNameStr.toString();
    parseTableInfo[2] = colTypeStr.toString();

    return parseTableInfo;
  }
Example #17
0
  /*
   * Copies a table in the MDB into the destination.
   * @param   name	of the table in the MDB file
   * @param   dest 	JdbcLink. Where you want to create the imported table
   * @return			number of rows imported
   * @see 	The name in destination may be prefixed using setPrefixForImportedTableNames
   */
  public int convertTable(String name, JdbcLink dest) throws IOException, SQLException {
    Table table = db.getTable(name);
    String insertName = ImportPrefix + name;
    List<Column> cols = table.getColumns();
    try {
      dest.exec("DROP TABLE IF EXISTS " + insertName); // $NON-NLS-1$

    } catch (Exception ex) {
      // don¨t mind
    }
    StringBuilder sb = new StringBuilder();
    sb.append("CREATE TABLE ").append(insertName).append("("); // $NON-NLS-1$ //$NON-NLS-2$
    for (Column c : cols) {
      sb.append(c.getName()).append(" ");
      switch (c.getType()) {
        case MEMO:
          sb.append("TEXT"); // $NON-NLS-1$
          break;
        case INT:
        case LONG:
          sb.append("INTEGER"); // $NON-NLS-1$
          break;
        case TEXT:
          sb.append("VARCHAR(255)"); // $NON-NLS-1$
          break;
        default:
          sb.append("VARCHAR(255)"); // $NON-NLS-1$
      }
      sb.append(","); // $NON-NLS-1$
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(");"); // $NON-NLS-1$
    dest.exec(sb.toString());
    Map<String, Object> row = null;
    int nrRows = 0;
    while ((row = table.getNextRow()) != null) {
      nrRows++;
      StringBuilder left = new StringBuilder();
      left.append("INSERT INTO ").append(insertName).append("("); // $NON-NLS-1$ //$NON-NLS-2$
      StringBuilder right = new StringBuilder();
      right.append(" VALUES("); // $NON-NLS-1$
      for (String key : row.keySet()) {
        left.append(key).append(","); // $NON-NLS-1$
        right.append("?,"); // $NON-NLS-1$
      }
      left.deleteCharAt(left.length() - 1);
      right.deleteCharAt(right.length() - 1);
      left.append(") ").append(right).append(");"); // $NON-NLS-1$ //$NON-NLS-2$
      PreparedStatement ps = dest.prepareStatement(left.toString());
      int i = 1;
      for (String key : row.keySet()) {
        ps.setObject(i++, row.get(key));
      }
      ps.execute();
    }
    return nrRows;
  }
 private void removeTrailingWhitespace(StringBuilder sb) {
   while (sb.length() > 0 && (sb.charAt(0) == ' ' || sb.charAt(0) == '\t')) // trim left
   sb.deleteCharAt(0);
   while (sb.length() > 0
       && (sb.charAt(sb.length() - 1) == ' ' || sb.charAt(sb.length() - 1) == '\t')) // trim right
   sb.deleteCharAt(sb.length() - 1);
   if (sb.length() != 0
       && sb.lastIndexOf(K5Symbol.DEFAULT_STATEMENT_SEPARATOR_STRING)
           == (sb.length() - K5Symbol.DEFAULT_STATEMENT_SEPARATOR_STRING.length()))
     sb.delete(sb.length() - K5Symbol.DEFAULT_STATEMENT_SEPARATOR_STRING.length(), sb.length());
 }
Example #19
0
 protected static void fixWhitespace(StringBuilder translation, String source) {
   if (source.startsWith("\n") && translation.charAt(0) != '\n') {
     translation.insert(0, '\n');
   } else if (!source.startsWith("\n") && translation.charAt(0) == '\n') {
     translation.deleteCharAt(0);
   }
   if (source.endsWith("\n") && translation.charAt(translation.length() - 1) != '\n') {
     translation.append('\n');
   } else if (!source.endsWith("\n") && translation.charAt(translation.length() - 1) == '\n') {
     translation.deleteCharAt(translation.length() - 1);
   }
 }
Example #20
0
  public StringLiteral(GOLDParser parser) {
    // The null test is being performed because this class is used in a test where the parser
    // is not completely initialized.  In production, the current reduction will always be set.
    String str =
        parser.getCurrentReduction() == null
            ? "\"\""
            : parser.getCurrentReduction().get(0).asString();

    StringBuilder sb = new StringBuilder(str);
    sb.deleteCharAt(sb.length() - 1);
    sb.deleteCharAt(0);
    setValue(new Variable(sb.toString()));
  }
  @Override
  public String getText() {
    StringBuilder text = new StringBuilder();

    //		text.append (String.format ("Total entries : %,6d%n", totalEntries));
    //		text.append (String.format ("Separators    : %,6d%n", totalSeparators));
    //		text.append (String.format ("Offset        : %,6d   %04X%n%n", dictionaryPtr,
    // dictionaryPtr));

    int count = 0;
    int ptr = dictionaryPtr + totalSeparators + 4;

    for (ZString word : dictionary.values()) {
      text.append(
          String.format(
              "%04X   %3d   %-6s   %s",
              ptr,
              count++,
              word.value,
              HexFormatter.getHexString(buffer, ptr + 4, entryLength - 4)));
      int b1 = buffer[ptr + 4] & 0xFF;
      int b2 = buffer[ptr + 5] & 0xFF;
      int b3 = buffer[ptr + 6] & 0xFF;
      if (b1 == 65) text.append(String.format("  %3d%n", b2));
      else if (b1 == 98 || b1 == 0xC0 || b1 == 0x44) text.append(String.format("  %3d%n", b3));
      else text.append("\n");
      ptr += entryLength;
    }

    if (true) {
      int lastValue = 0;
      for (List<WordEntry> list : synonymList.values()) {
        WordEntry wordEntry = list.get(0);
        if (wordEntry.value != lastValue) {
          lastValue = wordEntry.value;
          text.append("\n");
        }

        if (wordEntry.value == 0x80) // nouns are all in one entry
        {
          for (WordEntry we : list) text.append(we + "\n");
          text.deleteCharAt(text.length() - 1);
        } else text.append(wordEntry);
        if ((buffer[wordEntry.word.startPtr + 4] & 0x10) != 0) text.append("  property");
        text.append("\n");
      }
    }

    text.deleteCharAt(text.length() - 1);
    return text.toString();
  }
Example #22
0
 @Override
 /**
  * Formats a collection If the parenthesis are [ and ] An empty collection is rendered as [] A
  * collection with one single line item is rendered as [object] A collection with multiple items
  * is rendered as [ item, item_line1 item_line2, item ]
  */
 public String toString() {
   Brackets br = getBrackets();
   StringBuilder sb = new StringBuilder();
   sb.append(br.open);
   try {
     String item = nextItem();
     if (item != null) {
       // there is at least one item
       BufferedReader reader;
       String line;
       // number of lines
       int count = 0;
       sb.append('\n');
       // iterate over all objects in the list
       do {
         // iterate over every single line in the item
         // to prepend whitespace for indentation
         reader = new BufferedReader(new StringReader(item));
         line = reader.readLine();
         // line shouldn't be null, which object would map to an empty string?
         sb.append("  ").append(line);
         ++count;
         while ((line = reader.readLine()) != null) {
           sb.append("\n  ").append(line);
           ++count;
         }
         ;
         sb.append(",\n");
       } while ((item = nextItem()) != null);
       // remove the last ,
       sb.deleteCharAt(sb.length() - 2);
       if (count == 1) {
         // also remove the first and last newline
         // also remove first indentation
         sb.deleteCharAt(sb.length() - 1);
         sb.delete(1, 4);
       }
     }
   } catch (IOException e) {
     // StringBuffers don't have IOExceptions
     assert false;
   }
   sb.append(br.close);
   return sb.toString();
 }
Example #23
0
  private String getPhongInfoFromGame(int zoneId, boolean isMobile) {
    RoomDB db = new RoomDB();

    List<NRoomEntity> rooms = db.getRooms(zoneId);
    StringBuilder sb = new StringBuilder();
    if (isMobile) {
      if (rooms != null) {
        int roomSize = rooms.size();
        for (int i = 0; i < roomSize; i++) {
          NRoomEntity entity = rooms.get(i);
          int playing;
          if (entity.getPhong() == null) {
            playing = 0;
          } else {
            playing = entity.getPhong().getPlaying();
          }

          sb.append(entity.getId()).append(AIOConstants.SEPERATOR_ELEMENT);
          sb.append(playing).append(AIOConstants.SEPERATOR_ELEMENT);
          sb.append(entity.getLv()).append(AIOConstants.SEPERATOR_ARRAY);
        }
      }

      if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
      }
    } else {
      if (rooms != null) {

        int roomSize = rooms.size();
        for (int i = 0; i < roomSize; i++) {
          NRoomEntity entity = rooms.get(i);
          int playing;
          if (entity.getPhong() == null) {
            playing = 0;
          } else {
            playing = entity.getPhong().getPlaying();
          }

          sb.append(entity.getId()).append(AIOConstants.SEPERATOR_BYTE_1);
          sb.append(playing).append(AIOConstants.SEPERATOR_BYTE_1);
          sb.append(entity.getLv()).append(AIOConstants.SEPERATOR_BYTE_2);
        }
      }

      if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
      }
    }
    return sb.toString();
  }
Example #24
0
  public String nysiis(String str) {
    if (str == null) {
      return null;
    }
    str = SoundexUtils.clean(str);
    if (str.length() == 0) {
      return str;
    }
    str = PAT_MAC.matcher(str).replaceFirst("MCC");
    str = PAT_KN.matcher(str).replaceFirst("NN");
    str = PAT_K.matcher(str).replaceFirst("C");
    str = PAT_PH_PF.matcher(str).replaceFirst("FF");
    str = PAT_SCH.matcher(str).replaceFirst("SSS");

    str = PAT_EE_IE.matcher(str).replaceFirst("Y");
    str = PAT_DT_ETC.matcher(str).replaceFirst("D");

    StringBuilder key = new StringBuilder(str.length());
    key.append(str.charAt(0));

    char[] chars = str.toCharArray();
    int len = chars.length;
    for (int i = 1; i < len; i++) {
      char next = i < len - 1 ? chars[(i + 1)] : ' ';
      char aNext = i < len - 2 ? chars[(i + 2)] : ' ';
      char[] transcoded = transcodeRemaining(chars[(i - 1)], chars[i], next, aNext);
      System.arraycopy(transcoded, 0, chars, i, transcoded.length);
      if (chars[i] != chars[(i - 1)]) {
        key.append(chars[i]);
      }
    }
    if (key.length() > 1) {
      char lastChar = key.charAt(key.length() - 1);
      if (lastChar == 'S') {
        key.deleteCharAt(key.length() - 1);
        lastChar = key.charAt(key.length() - 1);
      }
      if (key.length() > 2) {
        char last2Char = key.charAt(key.length() - 2);
        if ((last2Char == 'A') && (lastChar == 'Y')) {
          key.deleteCharAt(key.length() - 2);
        }
      }
      if (lastChar == 'A') {
        key.deleteCharAt(key.length() - 1);
      }
    }
    String string = key.toString();
    return isStrict() ? string.substring(0, Math.min(6, string.length())) : string;
  }
Example #25
0
  /**
   * Remove leading and trailing whitespace
   *
   * @param input
   */
  private static void trim(final StringBuilder input) {
    int length = input.length();
    int breakLength = BREAK.length();

    while (length > 0) {
      if (input.indexOf(BREAK) == 0) input.delete(0, breakLength);
      else if (length >= breakLength && input.lastIndexOf(BREAK) == length - breakLength)
        input.delete(length - breakLength, length);
      else if (Character.isWhitespace(input.charAt(0))) input.deleteCharAt(0);
      else if (Character.isWhitespace(input.charAt(length - 1))) input.deleteCharAt(length - 1);
      else break;
      length = input.length();
    }
  }
Example #26
0
 /*
  * Enabled aggressive block sorting
  */
 public String nysiis(String charSequence) {
     int n2;
     void var1_3;
     if (charSequence == null) {
         return var1_3;
     }
     String string2 = SoundexUtils.clean(charSequence);
     if (string2.length() == 0) {
         return string2;
     }
     String string3 = PAT_MAC.matcher(string2).replaceFirst("MCC");
     String string4 = PAT_KN.matcher(string3).replaceFirst("NN");
     String string5 = PAT_K.matcher(string4).replaceFirst("C");
     String string6 = PAT_PH_PF.matcher(string5).replaceFirst("FF");
     String string7 = PAT_SCH.matcher(string6).replaceFirst("SSS");
     String string8 = PAT_EE_IE.matcher(string7).replaceFirst("Y");
     String string9 = PAT_DT_ETC.matcher(string8).replaceFirst("D");
     StringBuilder stringBuilder = new StringBuilder(string9.length());
     stringBuilder.append(string9.charAt(0));
     string9 = (String)string9.toCharArray();
     int n3 = string9.length;
     for (n2 = 1; n2 < n3; ++n2) {
         Object object = n2 < n3 - 1 ? (Object)string9[n2 + 1] : 32;
         Object object2 = n2 < n3 - 2 ? (Object)string9[n2 + 2] : 32;
         char[] arrc = Nysiis.transcodeRemaining((char)string9[n2 - 1], (char)string9[n2], (char)object, (char)object2);
         System.arraycopy(arrc, 0, string9, n2, arrc.length);
         if (string9[n2] == string9[n2 - 1]) continue;
         stringBuilder.append((char)string9[n2]);
     }
     if (stringBuilder.length() > 1) {
         n2 = n3 = (int)stringBuilder.charAt(stringBuilder.length() - 1);
         if (n3 == 83) {
             stringBuilder.deleteCharAt(stringBuilder.length() - 1);
             n2 = stringBuilder.charAt(stringBuilder.length() - 1);
         }
         if (stringBuilder.length() > 2 && stringBuilder.charAt(stringBuilder.length() - 2) == 'A' && n2 == 89) {
             stringBuilder.deleteCharAt(stringBuilder.length() - 2);
         }
         if (n2 == 65) {
             stringBuilder.deleteCharAt(stringBuilder.length() - 1);
         }
     }
     String string10 = string9 = stringBuilder.toString();
     if (!this.isStrict()) {
         return var1_3;
     }
     return string9.substring(0, Math.min(6, string9.length()));
 }
  /** {@inheritDoc} */
  @Override
  public synchronized void setAnalysisDataForFile(
      String filePath,
      String repository,
      AstNode binaryIndex,
      List<Usage> usages,
      List<String> types,
      List<String> imports)
      throws DatabaseAccessException {
    int fileId = ensureThatRecordExists(filePath, repository);
    int repoId = getRepoIdForRepoName(repository);

    QueryRunner run = new QueryRunner(dataSource);
    try {
      // Clears all types set for the file in a previous indexing process
      run.update(STMT_CLEAR_TYPES_FOR_FILE, fileId);
      // Clears all imports set for the file in a previous indexing procedure
      run.update(STMT_CLEAR_IMPORTS_FOR_FILE, fileId);
      // Sets the Binary index and the usages for the file
      run.update(STMT_SET_BINARY_INDEX_AND_USAGES_FOR_FILE, binaryIndex, usages, fileId);
      // Sets the types for the file, if any
      if (!(types.isEmpty())) {
        // extends the insert into statement by one line for each type in the list of types
        StringBuilder statement = new StringBuilder(STMT_CREATE_TYPES_FOR_FILE);
        String[] params = new String[types.size()];
        for (int i = 0; i < types.size(); i++) {
          statement.append("(?, ").append(fileId).append(", ").append(repoId).append("),");
          params[i] = types.get(i);
        }
        statement.deleteCharAt(statement.length() - 1);
        run.update(statement.toString(), (Object[]) params);
      }
      // Sets the imports for the file, if any
      if (!imports.isEmpty()) {
        // first build the import statement by adding all values
        StringBuilder importString = new StringBuilder(STMT_SET_IMPORTS_FOR_FILE);
        String[] params = new String[imports.size()];
        for (int i = 0; i < imports.size(); i++) {
          importString.append("(").append(fileId).append(", ?),");
          params[i] = imports.get(i);
        }
        importString.deleteCharAt(importString.length() - 1);
        run.update(importString.toString(), (Object[]) params);
      }
    } catch (SQLException ex) {
      throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex);
    }
  }
 public String Reduce(String w) {
   int done = 0;
   StringBuilder sb = new StringBuilder(w);
   // System.out.println("Checking "+w);
   while (done == 0) {
     done = 1;
     int i = 0;
     while (i < sb.length()) {
       //	System.out.println("*"+sb.length());
       //	System.out.println(i);
       if (sb.charAt(i) == this.barL.get(sb.charAt((i + 1) % (sb.length())))) {
         if (i == 0) {
           sb.delete(0, 2);
           done = 0;
           i = 0;
         } else if (i < sb.length() - 1) {
           sb.delete(i, i + 2);
           done = 0;
           i = 0;
         } else if (i == sb.length() - 1) {
           sb.deleteCharAt(i);
           sb.deleteCharAt(0);
           done = 0;
           i = 0;
         }
       } else i++;
     }
   }
   return sb.toString();
 }
Example #29
0
  /**
   * Formats a URI by adding a forward slash and removing the last forward slash from the URI.
   *
   * <p>e.g. some/random/uri/ -> /some/random/uri e.g. some/random/uri -> /some/random/uri e.g.
   * /some/random/uri/ -> /some/random/uri e.g. / -> / e.g. ////// -> /
   *
   * @param uri
   * @return
   */
  public static String formatUri(String uri) {
    if (StringUtilities.nullSafeStartsWith(uri, "\\")) {
      // windows file system
      return uri;
    }

    if (StringUtilities.isBlank(uri) || StringUtilities.nullSafeEqualsIgnoreCase("/", uri)) {
      return "/";
    }

    final StringBuilder externalName = new StringBuilder(uri);

    if (externalName.charAt(0) != '/') {
      externalName.insert(0, "/");
    }

    int doubleSlash = externalName.indexOf("//");

    while (doubleSlash > -1) {
      // removes leading '/'
      externalName.replace(doubleSlash, doubleSlash + 2, "/");
      doubleSlash = externalName.indexOf("//");
    }

    if (externalName.charAt(externalName.length() - 1) == '/' && externalName.length() != 1) {
      externalName.deleteCharAt(externalName.length() - 1);
    }

    return externalName.toString();
  }
 /**
  * takes an individual line and cleans it by removing comments and extra whitespace
  *
  * @param line
  * @return cleaned line with comments removed and extra whitespace removed
  *     <p>NOTE: can handle spaces, can't currently handle tab characters
  */
 public static String cleanLine(String line) {
   line = line.replaceAll("\\s+", " ");
   line = line.replaceAll(" =", "=");
   line = line.replaceAll("= ", "=");
   StringBuilder str = new StringBuilder();
   boolean lastCharSpace = true;
   for (int i = 0; i < line.length(); i++) {
     // exit the loop if we're at a comment
     if (line.charAt(i) == '#') {
       break;
     } else if (line.charAt(i) == ' ' && !lastCharSpace) {
       lastCharSpace = true;
       str.append(line.charAt(i));
     } else if (line.charAt(i) == ' ') {
       lastCharSpace = true;
     } else if (!lastCharSpace) {
       str.append(line.charAt(i));
     } else {
       lastCharSpace = false;
       str.append(line.charAt(i));
     }
   }
   // now we're going to loop through again and just delete all the
   // extra spaces that might exist at the end of the string
   for (int i = str.length() - 1; i >= 0; --i) {
     if (str.charAt(str.length() - 1) == ' ') {
       str.deleteCharAt(str.length() - 1);
     } else {
       break;
     }
   }
   return str.toString();
 }