/**
   * Performs OCR operation.
   *
   * @param imageList a list of <code>IIOImage</code> objects
   * @param rect the bounding rectangle defines the region of the image to be recognized. A
   *     rectangle of zero dimension or <code>null</code> indicates the whole image.
   * @return the recognized text
   * @throws TesseractException
   */
  public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException {
    init();
    setTessVariables();

    try {
      StringBuilder sb = new StringBuilder();

      for (IIOImage oimage : imageList) {
        pageNum++;
        try {
          setImage(oimage.getRenderedImage(), rect);
          sb.append(getOCRText());
        } catch (IOException ioe) {
          // skip the problematic image
          logger.log(Level.SEVERE, ioe.getMessage(), ioe);
        }
      }

      if (hocr) {
        sb.insert(0, htmlBeginTag).append(htmlEndTag);
      }

      return sb.toString();
    } finally {
      dispose();
    }
  }
Beispiel #2
1
  private void initIfNeed() {
    if (myInitialized) return;
    myInitialized = true;
    for (Map.Entry<String, Pair<String, List<String>>> entry : myTree.entrySet()) {
      final String group = entry.getKey();
      if (CORE.equals(group)) continue;

      List<IdSet> idSets = new ArrayList<IdSet>();
      StringBuilder description = new StringBuilder();
      for (String idDescription : entry.getValue().getSecond()) {
        IdSet idSet = new IdSet(idDescription);
        String idSetTitle = idSet.getTitle();
        if (idSetTitle == null) continue;
        idSets.add(idSet);
        if (description.length() > 0) {
          description.append(", ");
        }
        description.append(idSetTitle);
      }
      myGroups.put(group, idSets);

      if (description.length() > MAX_DESCR_LENGTH) {
        int lastWord = description.lastIndexOf(",", MAX_DESCR_LENGTH);
        description.delete(lastWord, description.length()).append("...");
      }
      description.insert(0, "<html><body><center><i>");
      myDescriptions.put(group, description.toString());
    }
  }
 public List<Combat> addAttackers(Game game) {
   Map<Integer, Combat> engagements = new HashMap<Integer, Combat>();
   // useful only for two player games - will only attack first opponent
   UUID defenderId = game.getOpponents(playerId).iterator().next();
   List<Permanent> attackersList = super.getAvailableAttackers(defenderId, game);
   // use binary digits to calculate powerset of attackers
   int powerElements = (int) Math.pow(2, attackersList.size());
   StringBuilder binary = new StringBuilder();
   for (int i = powerElements - 1; i >= 0; i--) {
     Game sim = game.copy();
     binary.setLength(0);
     binary.append(Integer.toBinaryString(i));
     while (binary.length() < attackersList.size()) {
       binary.insert(0, "0");
     }
     for (int j = 0; j < attackersList.size(); j++) {
       if (binary.charAt(j) == '1') {
         setStoredBookmark(
             sim
                 .bookmarkState()); // makes it possible to UNDO a declared attacker with costs
                                    // from e.g. Propaganda
         if (!sim.getCombat()
             .declareAttacker(attackersList.get(j).getId(), defenderId, playerId, sim)) {
           sim.undo(playerId);
         }
       }
     }
     if (engagements.put(sim.getCombat().getValue().hashCode(), sim.getCombat()) != null) {
       logger.debug("simulating -- found redundant attack combination");
     } else if (logger.isDebugEnabled()) {
       logger.debug("simulating -- attack:" + sim.getCombat().getGroups().size());
     }
   }
   return new ArrayList<Combat>(engagements.values());
 }
Beispiel #4
1
  /**
   * Configures the basic escapes based on the configured options.
   *
   * @param options Options that will affect what is escaped.
   */
  private void setupEscapes(Options options) {
    escapes = new ArrayList<Escape>();

    // confusingly, this replaces single backslashes with double backslashes.
    // Man, I miss Groovy's slashy strings in these moments...
    escapes.add(new Escape("\\\\", "\\\\\\\\"));

    // creates an set of characters that are universally escaped.
    // these characters are wrapped in \Q...\E to ensure they aren't treated as special characters.
    StringBuilder chars = new StringBuilder("([\\Q`*_{}[]#");
    if (options.tables.isConvertedToText() && !options.tables.isRenderedAsCode()) {
      chars.append('|');
    }
    chars.append("\\E])");
    escapes.add(new Escape(chars.toString(), "\\\\$1"));

    // finally, escape certain characters only if they are leading characters
    StringBuilder leadingChars = new StringBuilder("^( ?+)([\\Q-+");
    if (options.definitionLists) {
      leadingChars.append(':');
    }
    leadingChars.append("\\E])");
    escapes.add(new Escape(leadingChars.toString(), "$1\\\\$2"));

    // setup the leading character reverser
    // this is a bit of a hack to undo leading character escapes.
    unescapeLeadingChars = Pattern.compile(leadingChars.insert(6, "\\\\").toString());
  }
    private String buildLabelText(
        @NotNull final String text,
        @NotNull final Map<TextRange, ParameterInfoUIContextEx.Flag> flagsMap) {
      final StringBuilder labelText = new StringBuilder(text);
      final String disabledTag = FLAG_TO_TAG.get(ParameterInfoUIContextEx.Flag.DISABLE);

      final Map<Integer, Integer> faultMap = new HashMap<>();
      if (isDisabledBeforeHighlight) {
        final String tag = getTag(disabledTag);
        labelText.insert(0, tag);
        faultMap.put(0, tag.length());
      }

      for (Map.Entry<TextRange, ParameterInfoUIContextEx.Flag> entry : flagsMap.entrySet()) {
        final TextRange highlightRange = entry.getKey();
        final ParameterInfoUIContextEx.Flag flag = entry.getValue();

        final String tagValue = FLAG_TO_TAG.get(flag);
        final String tag = getTag(tagValue);

        int startOffset = highlightRange.getStartOffset();
        int endOffset = highlightRange.getEndOffset() + tag.length();

        for (Map.Entry<Integer, Integer> entry1 : faultMap.entrySet()) {
          if (entry1.getKey() < highlightRange.getStartOffset()) {
            startOffset += entry1.getValue();
          }
          if (entry1.getKey() < highlightRange.getEndOffset()) {
            endOffset += entry1.getValue();
          }
        }

        if (flag == ParameterInfoUIContextEx.Flag.HIGHLIGHT && isDisabledBeforeHighlight) {
          final String disableCloseTag = getClosingTag(disabledTag);
          labelText.insert(startOffset, disableCloseTag);
          faultMap.put(highlightRange.getStartOffset(), disableCloseTag.length());
        }

        labelText.insert(startOffset, tag);
        faultMap.put(highlightRange.getStartOffset(), tag.length());

        final String endTag = getClosingTag(tagValue);
        labelText.insert(endOffset, endTag);
        faultMap.put(highlightRange.getEndOffset(), endTag.length());
      }
      return XmlStringUtil.wrapInHtml(labelText);
    }
  private void updateText() {
    StringBuilder sb = new StringBuilder();

    if (myShowSettingsBeforeRunCheckBox.isSelected()) {
      sb.append(ExecutionBundle.message("configuration.edit.before.run")).append(", ");
    }

    List<BeforeRunTask> tasks = myModel.getItems();
    if (!tasks.isEmpty()) {
      LinkedHashMap<BeforeRunTaskProvider, Integer> counter =
          new LinkedHashMap<BeforeRunTaskProvider, Integer>();
      for (BeforeRunTask task : tasks) {
        BeforeRunTaskProvider<BeforeRunTask> provider =
            BeforeRunTaskProvider.getProvider(
                myRunConfiguration.getProject(), task.getProviderId());
        if (provider != null) {
          Integer count = counter.get(provider);
          if (count == null) {
            count = task.getItemsCount();
          } else {
            count += task.getItemsCount();
          }
          counter.put(provider, count);
        }
      }
      for (Iterator<Map.Entry<BeforeRunTaskProvider, Integer>> iterator =
              counter.entrySet().iterator();
          iterator.hasNext(); ) {
        Map.Entry<BeforeRunTaskProvider, Integer> entry = iterator.next();
        BeforeRunTaskProvider provider = entry.getKey();
        String name = provider.getName();
        if (name.startsWith("Run ")) {
          name = name.substring(4);
        }
        sb.append(name);
        if (entry.getValue() > 1) {
          sb.append(" (").append(entry.getValue().intValue()).append(")");
        }
        if (iterator.hasNext()) sb.append(", ");
      }
    }
    if (sb.length() > 0) {
      sb.insert(0, ": ");
    }
    sb.insert(0, ExecutionBundle.message("before.launch.panel.title"));
    myListener.titleChanged(sb.toString());
  }
Beispiel #7
1
 @NotNull
 public static String rightJustify(@NotNull String text, int width, char fillChar) {
   final StringBuilder builder = new StringBuilder(text);
   for (int i = text.length(); i < width; i++) {
     builder.insert(0, fillChar);
   }
   return builder.toString();
 }
 /** Return next string in the sequence "a", "b", ... "z", "aa", "ab", ... */
 static String getNextDirName(String old) {
   StringBuilder sb = new StringBuilder(old);
   // go through and increment the first non-'z' char
   // counts back from the last char, so 'aa'->'ab', not 'ba'
   for (int ii = sb.length() - 1; ii >= 0; ii--) {
     char curChar = sb.charAt(ii);
     if (curChar < 'z') {
       sb.setCharAt(ii, (char) (curChar + 1));
       return sb.toString();
     }
     sb.setCharAt(ii, 'a');
   }
   sb.insert(0, 'a');
   return sb.toString();
 }
 @NotNull
 public static String getProjectRepresentationName(
     @NotNull String targetProjectPath, @Nullable String rootProjectPath) {
   if (rootProjectPath == null) {
     File rootProjectDir = new File(targetProjectPath);
     if (rootProjectDir.isFile()) {
       rootProjectDir = rootProjectDir.getParentFile();
     }
     return rootProjectDir.getName();
   }
   File rootProjectDir = new File(rootProjectPath);
   if (rootProjectDir.isFile()) {
     rootProjectDir = rootProjectDir.getParentFile();
   }
   File targetProjectDir = new File(targetProjectPath);
   if (targetProjectDir.isFile()) {
     targetProjectDir = targetProjectDir.getParentFile();
   }
   StringBuilder buffer = new StringBuilder();
   for (File f = targetProjectDir;
       f != null && !FileUtil.filesEqual(f, rootProjectDir);
       f = f.getParentFile()) {
     buffer.insert(0, f.getName()).insert(0, ":");
   }
   buffer.insert(0, rootProjectDir.getName());
   return buffer.toString();
 }
  private static Couple<Integer> composeText(
      StringBuilder sb,
      List<Pair<String, HighlightInfo>> list,
      int index,
      String text,
      int endPos,
      int startPos) {
    int i = index;
    while (i < list.size()) {
      Pair<String, HighlightInfo> pair = list.get(i);
      HighlightInfo info = pair.second;
      if (info.endOffset <= startPos) {
        break;
      }

      String severity = pair.first;
      HighlightInfo prev = i < list.size() - 1 ? list.get(i + 1).second : null;

      sb.insert(0, text.substring(info.endOffset, endPos));
      sb.insert(0, "</" + severity + ">");
      endPos = info.endOffset;
      if (prev != null && prev.endOffset > info.startOffset) {
        Couple<Integer> result = composeText(sb, list, i + 1, text, endPos, info.startOffset);
        i = result.first - 1;
        endPos = result.second;
      }
      sb.insert(0, text.substring(info.startOffset, endPos));
      sb.insert(0, "<" + severity + " descr=\"" + info.getDescription() + "\">");

      endPos = info.startOffset;
      i++;
    }

    return Couple.newOne(i, endPos);
  }
  public void testPsi2DocSurround() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.replaceString(document, 3, 5, "3a4");
    buffer.replace(3, 5, "3a4");

    synchronizer.insertString(document, 3, "b");
    buffer.insert(3, "b");

    synchronizer.insertString(document, 7, "d");
    buffer.insert(7, "d");

    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();
    assertEquals(3, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 7);
  }
Beispiel #12
0
  public String toMenuLocationDebug(final String profileID, final Locale locale) {
    final String SEPARATOR =
        LocaleHelper.getLocalizedMessage(locale, Config.Display_SettingNavigationSeparator, null);
    final StringBuilder sb = new StringBuilder();

    PwmSettingCategory nextCategory = this;
    while (nextCategory != null) {
      if (nextCategory != this) {
        sb.insert(0, nextCategory.getLabel(locale) + SEPARATOR);
      } else {
        sb.insert(0, nextCategory.getLabel(locale));
      }
      nextCategory = nextCategory.getParent();
    }

    if (this.hasProfiles()) {
      if (profileID != null) {
        sb.append(SEPARATOR);
        sb.append(profileID);
      } else {
        final String NULL_PROFILE =
            LocaleHelper.getLocalizedMessage(
                locale, Config.Display_SettingNavigationNullProfile, null);
        sb.append(SEPARATOR);
        sb.append(NULL_PROFILE);
      }
    }

    return sb.toString();
  }
Beispiel #13
0
 private void applyPrefix(StringBuilder sql, String trimmedUppercaseSql) {
   if (!prefixApplied) {
     prefixApplied = true;
     for (String toRemove : prefixesToOverride) {
       if (trimmedUppercaseSql.startsWith(toRemove)) {
         sql.delete(0, toRemove.trim().length());
         break;
       }
     }
     if (prefix != null) {
       sql.insert(0, " ");
       sql.insert(0, prefix);
     }
   }
 }
  private static Couple<Integer> composeText(
      StringBuilder sb,
      List<Pair<String, HighlightInfo>> list,
      int index,
      String text,
      int endPos,
      int startPos,
      boolean showAttributesKeys) {
    int i = index;
    while (i < list.size()) {
      Pair<String, HighlightInfo> pair = list.get(i);
      HighlightInfo info = pair.second;
      if (info.endOffset <= startPos) {
        break;
      }

      String severity = pair.first;
      HighlightInfo prev = i < list.size() - 1 ? list.get(i + 1).second : null;

      sb.insert(0, text.substring(info.endOffset, endPos));
      sb.insert(0, "</" + severity + ">");
      endPos = info.endOffset;
      if (prev != null && prev.endOffset > info.startOffset) {
        Couple<Integer> result =
            composeText(sb, list, i + 1, text, endPos, info.startOffset, showAttributesKeys);
        i = result.first - 1;
        endPos = result.second;
      }
      sb.insert(0, text.substring(info.startOffset, endPos));

      String str =
          "<"
              + severity
              + " descr=\""
              + StringUtil.escapeQuotes(String.valueOf(info.getDescription()))
              + "\"";
      if (showAttributesKeys) {
        str += " textAttributesKey=\"" + info.forcedTextAttributesKey + "\"";
      }
      str += ">";
      sb.insert(0, str);

      endPos = info.startOffset;
      i++;
    }

    return Couple.of(i, endPos);
  }
  public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);
    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();

    for (int i = 0; i < 10; i++) {
      synchronizer.insertString(document, i, "" + i);
      buffer.insert(i, "" + i);
    }

    assertEquals(1, affectedFragments.size());
    synchronizer.replaceString(document, 0, 20, "0123456789");
    buffer.replace(0, 20, "0123456789");

    assertEquals(1, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 5);
  }
 public void insertEmotion(String emotionChar) {
   String ori = content.getText().toString();
   int index = content.getSelectionStart();
   StringBuilder stringBuilder = new StringBuilder(ori);
   stringBuilder.insert(index, emotionChar);
   content.setText(stringBuilder.toString());
   content.setSelection(index + emotionChar.length());
 }
  public static String composeText(
      final Map<String, ExpectedHighlightingSet> types,
      Collection<HighlightInfo> infos,
      String text) {
    // filter highlighting data and map each highlighting to a tag name
    List<Pair<String, HighlightInfo>> list =
        ContainerUtil.mapNotNull(
            infos,
            new NullableFunction<HighlightInfo, Pair<String, HighlightInfo>>() {
              @Override
              public Pair<String, HighlightInfo> fun(HighlightInfo info) {
                for (Map.Entry<String, ExpectedHighlightingSet> entry : types.entrySet()) {
                  final ExpectedHighlightingSet set = entry.getValue();
                  if (set.enabled
                      && set.severity == info.getSeverity()
                      && set.endOfLine == info.isAfterEndOfLine()) {
                    return Pair.create(entry.getKey(), info);
                  }
                }
                return null;
              }
            });

    // sort filtered highlighting data by end offset in descending order
    Collections.sort(
        list,
        new Comparator<Pair<String, HighlightInfo>>() {
          @Override
          public int compare(Pair<String, HighlightInfo> o1, Pair<String, HighlightInfo> o2) {
            HighlightInfo i1 = o1.second;
            HighlightInfo i2 = o2.second;

            int byEnds = i2.endOffset - i1.endOffset;
            if (byEnds != 0) return byEnds;

            if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
              int byStarts = i1.startOffset - i2.startOffset;
              if (byStarts != 0) return byStarts;
            } else {
              int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
              if (byEOL != 0) return byEOL;
            }

            int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
            if (bySeverity != 0) return bySeverity;

            return Comparing.compare(i1.getDescription(), i2.getDescription());
          }
        });

    // combine highlighting data with original text
    StringBuilder sb = new StringBuilder();
    Couple<Integer> result = composeText(sb, list, 0, text, text.length(), 0);
    sb.insert(0, text.substring(0, result.second));
    return sb.toString();
  }
  public void testPsi2DocForwardRangesChanges() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.replaceString(document, 4, 5, "3a4");
    buffer.replace(4, 5, "3a4");

    synchronizer.insertString(document, 7, "b");
    buffer.insert(7, "b");

    synchronizer.insertString(document, 1, "b");
    buffer.insert(1, "b");

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 3, 8);
  }
 private String xbuildColumnString() {
   final String c = ", ";
   final StringBuilder sb = new StringBuilder();
   sb.append(c).append(_vInVarchar);
   sb.append(c).append(_vOutVarchar);
   if (sb.length() > 0) {
     sb.delete(0, c.length());
   }
   sb.insert(0, "{").append("}");
   return sb.toString();
 }
Beispiel #20
0
 /** @return The view string of columns. (NotNull) */
 public String toString() {
   String delimiter = ",";
   StringBuilder sb = new StringBuilder();
   sb.append(delimiter).append(getTestclass());
   sb.append(delimiter).append(getDescription());
   if (sb.length() > 0) {
     sb.delete(0, delimiter.length());
   }
   sb.insert(0, "{").append("}");
   return sb.toString();
 }
Beispiel #21
0
 /** @return The view string of columns. (NotNull) */
 public String toString() {
   String delimiter = ",";
   StringBuilder sb = new StringBuilder();
   sb.append(delimiter).append(getScenariotype());
   sb.append(delimiter).append(getDescription());
   sb.append(delimiter).append(getNumericweight());
   sb.append(delimiter).append(getNotes());
   if (sb.length() > 0) {
     sb.delete(0, delimiter.length());
   }
   sb.insert(0, "{").append("}");
   return sb.toString();
 }
  public void testPsi2Doc1() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.insertString(document, 3, "a");
    buffer.insert(3, "a");

    synchronizer.commitTransaction(this.document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 6);
  }
  /** @return The view string of columns. (NotNull) */
  public String toString() {
    final String delimiter = ",";
    final StringBuilder sb = new StringBuilder();

    sb.append(delimiter).append(getId());
    sb.append(delimiter).append(getName());
    sb.append(delimiter).append(getHireDate());
    sb.append(delimiter).append(getDeptId());
    sb.append(delimiter).append(getVersionNo());

    sb.delete(0, delimiter.length());
    sb.insert(0, "{").append("}");
    return sb.toString();
  }
Beispiel #24
0
 /** @return The view string of columns. (NotNull) */
 public String toString() {
   String delimiter = ",";
   StringBuilder sb = new StringBuilder();
   sb.append(delimiter).append(getPlanid());
   sb.append(delimiter).append(getCategory());
   sb.append(delimiter).append(getName());
   sb.append(delimiter).append(getAuthor());
   sb.append(delimiter).append(getNotes());
   sb.append(delimiter).append(getTestplan());
   if (sb.length() > 0) {
     sb.delete(0, delimiter.length());
   }
   sb.insert(0, "{").append("}");
   return sb.toString();
 }
Beispiel #25
0
 @Override
 public void selectAttackers(Game game, UUID attackingPlayerId) {
   // useful only for two player games - will only attack first opponent
   UUID defenderId = game.getOpponents(playerId).iterator().next();
   List<Permanent> attackersList = super.getAvailableAttackers(game);
   // use binary digits to calculate powerset of attackers
   int powerElements = (int) Math.pow(2, attackersList.size());
   int value = rnd.nextInt(powerElements);
   StringBuilder binary = new StringBuilder();
   binary.append(Integer.toBinaryString(value));
   while (binary.length() < attackersList.size()) {
     binary.insert(0, "0"); // pad with zeros
   }
   for (int i = 0; i < attackersList.size(); i++) {
     if (binary.charAt(i) == '1')
       game.getCombat().declareAttacker(attackersList.get(i).getId(), defenderId, game);
   }
   actionCount++;
 }
  public static int solution(int X) {
    // identical adjacent digits
    // remove one from the group
    // largest possible

    int curMax = Integer.MIN_VALUE;

    StringBuilder sb = new StringBuilder("" + X);

    // identify groups
    for (int i = 1; i < sb.length(); i++) {
      // group
      if (sb.charAt(i - 1) == sb.charAt(i)) {
        char ch = sb.charAt(i);
        sb.replace(i, i + 1, "");
        curMax = Math.max(curMax, Integer.parseInt(sb.toString()));
        sb.insert(i, ch);
      }
    }
    return curMax;
  }
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case CAMERA_RESULT:
          if (TextUtils.isEmpty(content.getText().toString())) {
            content.setText(getString(R.string.share_pic));
            content.setSelection(content.getText().toString().length());
          }

          picPath = getPicPathFromUri(imageFileUri);
          havePic.setVisibility(View.VISIBLE);
          break;
        case PIC_RESULT:
          if (TextUtils.isEmpty(content.getText().toString())) {
            content.setText(getString(R.string.share_pic));
            content.setSelection(content.getText().toString().length());
          }

          Uri imageFileUri = intent.getData();
          picPath = getPicPathFromUri(imageFileUri);
          havePic.setVisibility(View.VISIBLE);
          break;
        case AT_USER:
          String name = intent.getStringExtra("name");
          String ori = content.getText().toString();
          int index = content.getSelectionStart();
          StringBuilder stringBuilder = new StringBuilder(ori);
          stringBuilder.insert(index, name);
          content.setText(stringBuilder.toString());
          content.setSelection(index + name.length());
          break;
      }
    }
  }
  public static String composeText(
      final Map<String, ExpectedHighlightingSet> types,
      Collection<HighlightInfo> infos,
      String text) {
    // filter highlighting data and map each highlighting to a tag name
    List<Pair<String, HighlightInfo>> list =
        ContainerUtil.mapNotNull(
            infos,
            (NullableFunction<HighlightInfo, Pair<String, HighlightInfo>>)
                info -> {
                  for (Map.Entry<String, ExpectedHighlightingSet> entry : types.entrySet()) {
                    final ExpectedHighlightingSet set = entry.getValue();
                    if (set.enabled
                        && set.severity == info.getSeverity()
                        && set.endOfLine == info.isAfterEndOfLine()) {
                      return Pair.create(entry.getKey(), info);
                    }
                  }
                  return null;
                });

    boolean showAttributesKeys = false;
    for (ExpectedHighlightingSet eachSet : types.values()) {
      for (HighlightInfo eachInfo : eachSet.infos) {
        if (eachInfo.forcedTextAttributesKey != null) {
          showAttributesKeys = true;
          break;
        }
      }
    }

    // sort filtered highlighting data by end offset in descending order
    Collections.sort(
        list,
        (o1, o2) -> {
          HighlightInfo i1 = o1.second;
          HighlightInfo i2 = o2.second;

          int byEnds = i2.endOffset - i1.endOffset;
          if (byEnds != 0) return byEnds;

          if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
            int byStarts = i1.startOffset - i2.startOffset;
            if (byStarts != 0) return byStarts;
          } else {
            int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
            if (byEOL != 0) return byEOL;
          }

          int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
          if (bySeverity != 0) return bySeverity;

          return Comparing.compare(i1.getDescription(), i2.getDescription());
        });

    // combine highlighting data with original text
    StringBuilder sb = new StringBuilder();
    Couple<Integer> result = composeText(sb, list, 0, text, text.length(), 0, showAttributesKeys);
    sb.insert(0, text.substring(0, result.second));
    return sb.toString();
  }
Beispiel #29
0
  private InternalSearchHit.InternalNestedIdentity getInternalNestedIdentity(
      SearchContext context,
      int nestedSubDocId,
      LeafReaderContext subReaderContext,
      DocumentMapper documentMapper,
      ObjectMapper nestedObjectMapper)
      throws IOException {
    int currentParent = nestedSubDocId;
    ObjectMapper nestedParentObjectMapper;
    StringBuilder field = new StringBuilder();
    ObjectMapper current = nestedObjectMapper;
    InternalSearchHit.InternalNestedIdentity nestedIdentity = null;
    do {
      Filter parentFilter;
      nestedParentObjectMapper = documentMapper.findParentObjectMapper(current);
      if (field.length() != 0) {
        field.insert(0, '.');
      }
      field.insert(0, current.name());
      if (nestedParentObjectMapper != null) {
        if (nestedParentObjectMapper.nested().isNested() == false) {
          current = nestedParentObjectMapper;
          continue;
        }
        parentFilter = nestedParentObjectMapper.nestedTypeFilter();
      } else {
        parentFilter = Queries.newNonNestedFilter();
      }

      Filter childFilter = nestedObjectMapper.nestedTypeFilter();
      if (childFilter == null) {
        current = nestedParentObjectMapper;
        continue;
      }
      // We can pass down 'null' as acceptedDocs, because we're fetching matched docId that matched
      // in the query phase.
      DocIdSet childDocSet = childFilter.getDocIdSet(subReaderContext, null);
      if (childDocSet == null) {
        current = nestedParentObjectMapper;
        continue;
      }
      DocIdSetIterator childIter = childDocSet.iterator();
      if (childIter == null) {
        current = nestedParentObjectMapper;
        continue;
      }

      BitDocIdSet parentBitSet =
          context
              .bitsetFilterCache()
              .getBitDocIdSetFilter(parentFilter)
              .getDocIdSet(subReaderContext);
      BitSet parentBits = parentBitSet.bits();

      int offset = 0;
      int nextParent = parentBits.nextSetBit(currentParent);
      for (int docId = childIter.advance(currentParent + 1);
          docId < nextParent && docId != DocIdSetIterator.NO_MORE_DOCS;
          docId = childIter.nextDoc()) {
        offset++;
      }
      currentParent = nextParent;
      current = nestedObjectMapper = nestedParentObjectMapper;
      nestedIdentity =
          new InternalSearchHit.InternalNestedIdentity(field.toString(), offset, nestedIdentity);
      field = new StringBuilder();
    } while (current != null);
    return nestedIdentity;
  }
Beispiel #30
0
    @Override
    public String process(File page, Map<String, String> query) {
      loadContigs();

      if (query.get("contigName").matches("^[ACGT]+$")) {
        contigs.put("manual", query.get("contigName"));
        query.put("contigName", "manual");
      } else if (query.get("contigName").matches("^Pf3D7.+$")) {
        String[] pieces = query.get("contigName").split("[:-]");

        int start = Integer.valueOf(pieces[1].replaceAll(",", ""));
        int end = Integer.valueOf(pieces[2].replaceAll(",", ""));

        ReferenceSequence rseq = REF.getSubsequenceAt(pieces[0], start, end);
        contigs.put("manual", new String(rseq.getBases()));
        query.put("contigName", "manual");
      }

      if (query.containsKey("contigName")
          && contigs.containsKey(query.get("contigName"))
          && graphs.containsKey(query.get("graphName"))) {
        boolean showLinks = query.get("showLinks").equals("links_on");

        String contig = contigs.get(query.get("contigName"));
        String originalContig = contigs.get(query.get("contigName"));
        String refFormattedString = "";
        String kmerOrigin = "";

        if (metrics.containsKey(query.get("contigName"))) {
          String[] loc = metrics.get(query.get("contigName")).get("canonicalLocus").split("[:-]");
          if (!loc[0].equals("*")) {
            boolean isRc = metrics.get(query.get("contigName")).get("isRcCanonical").equals("1");

            if (isRc) {
              contig = SequenceUtils.reverseComplement(contig);
              originalContig = SequenceUtils.reverseComplement(originalContig);
            }

            int locStart = Integer.valueOf(loc[1]);
            int locEnd = Integer.valueOf(loc[2]);

            Cigar cigar =
                cigarStringToCigar(metrics.get(query.get("contigName")).get("cigarCanonical"));
            if (cigar.getCigarElement(0).getOperator().equals(CigarOperator.S)) {
              locStart -= cigar.getCigarElement(0).getLength();
            }

            if (cigar
                .getCigarElement(cigar.getCigarElements().size() - 1)
                .getOperator()
                .equals(CigarOperator.S)) {
              locEnd += cigar.getCigarElement(cigar.getCigarElements().size() - 1).getLength();
            }

            String ref = new String(REF.getSubsequenceAt(loc[0], locStart, locEnd).getBases());

            StringBuilder refFormatted = new StringBuilder();
            int pos = 0;
            for (CigarElement ce : cigar.getCigarElements()) {
              CigarOperator co = ce.getOperator();
              switch (co) {
                case S:
                  refFormatted.append(ref.substring(pos, pos + ce.getLength()).toLowerCase());
                  break;
                case M:
                  refFormatted.append(ref.substring(pos, pos + ce.getLength()));
                  break;
                case I:
                  refFormatted.append(StringUtils.repeat("-", ce.getLength()));
                  break;
              }

              if (ce.getOperator().consumesReferenceBases()) {
                pos += ce.getLength();
              }
            }

            refFormattedString = refFormatted.toString();

            kmerOrigin = metrics.get(query.get("contigName")).get("kmerOrigin");
          }
        }

        CortexGraph cg = graphs.get(query.get("graphName"));

        String sampleName = cg.getColor(0).getSampleName();
        Set<CortexLinksMap> links = new HashSet<CortexLinksMap>();
        if (LINKS != null && !LINKS.isEmpty()) {
          for (CortexLinksMap link : LINKS) {
            if (sampleName.equals(link.getCortexLinks().getColor(0).getSampleName())) {
              links.add(link);
            }
          }
        }

        Set<String> contigKmers = new HashSet<String>();
        for (int i = 0; i <= contig.length() - cg.getKmerSize(); i++) {
          String curKmer = contig.substring(i, i + cg.getKmerSize());

          contigKmers.add(curKmer);
        }

        StringBuilder firstFlank = new StringBuilder();
        String firstKmer = contig.substring(0, cg.getKmerSize());
        Set<String> pks = CortexUtils.getPrevKmers(cg, firstKmer, 0);
        Set<String> usedPrevKmers = new HashSet<String>();
        usedPrevKmers.add(firstKmer);
        while (pks.size() == 1 && usedPrevKmers.size() <= 100) {
          String kmer = pks.iterator().next();
          firstFlank.insert(0, kmer.charAt(0));

          if (usedPrevKmers.contains(kmer)) {
            break;
          }
          usedPrevKmers.add(kmer);

          pks = CortexUtils.getPrevKmers(cg, kmer, 0);
        }

        StringBuilder lastFlank = new StringBuilder();
        String lastKmer = contig.substring(contig.length() - cg.getKmerSize(), contig.length());
        Set<String> nks = CortexUtils.getNextKmers(cg, lastKmer, 0);
        Set<String> usedNextKmers = new HashSet<String>();
        usedNextKmers.add(lastKmer);
        while (nks.size() == 1 && usedNextKmers.size() <= 100) {
          String kmer = nks.iterator().next();
          lastFlank.append(kmer.charAt(kmer.length() - 1));

          if (usedNextKmers.contains(kmer)) {
            break;
          }
          usedNextKmers.add(kmer);

          nks = CortexUtils.getNextKmers(cg, kmer, 0);
        }

        contig = firstFlank.toString() + contig + lastFlank.toString();

        DirectedGraph<CtxVertex, MultiEdge> g =
            new DefaultDirectedGraph<CtxVertex, MultiEdge>(MultiEdge.class);
        for (int i = 0; i <= contig.length() - cg.getKmerSize(); i++) {
          String curKmer = contig.substring(i, i + cg.getKmerSize());
          CortexKmer ck = new CortexKmer(curKmer);
          CtxVertex curVer =
              new CtxVertex(
                  curKmer,
                  i,
                  contigKmers.contains(curKmer) ? VertexType.CONTIG : VertexType.CLIPPED,
                  cg.findRecord(ck));

          g.addVertex(curVer);

          String expectedPrevKmer =
              (i > 0) ? contig.substring(i - 1, i - 1 + cg.getKmerSize()) : "";
          String expectedNextKmer =
              (i < contig.length() - cg.getKmerSize())
                  ? contig.substring(i + 1, i + 1 + cg.getKmerSize())
                  : "";

          Set<String> prevKmers = CortexUtils.getPrevKmers(cg, curKmer, 0);
          for (String prevKmer : prevKmers) {
            if (!expectedPrevKmer.equals(prevKmer)) {
              CortexKmer pk = new CortexKmer(prevKmer);
              CtxVertex prevVer = new CtxVertex(prevKmer, i - 1, VertexType.IN, cg.findRecord(pk));

              MultiEdge me =
                  g.containsEdge(prevVer, curVer) ? g.getEdge(prevVer, curVer) : new MultiEdge();
              me.addGraphName(cg.getCortexFile().getName());

              g.addVertex(prevVer);
              g.addEdge(prevVer, curVer, me);
            }
          }

          Set<String> nextKmers = CortexUtils.getNextKmers(cg, curKmer, 0);
          for (String nextKmer : nextKmers) {
            if (!expectedNextKmer.equals(nextKmer)) {
              CortexKmer nk = new CortexKmer(nextKmer);
              CtxVertex nextVer = new CtxVertex(nextKmer, i + 1, VertexType.OUT, cg.findRecord(nk));

              MultiEdge me =
                  g.containsEdge(curVer, nextVer) ? g.getEdge(curVer, nextVer) : new MultiEdge();
              me.addGraphName(cg.getCortexFile().getName());

              g.addVertex(nextVer);
              g.addEdge(curVer, nextVer, me);
            }
          }
        }

        Set<Map<String, Object>> verticesWithLinks = new HashSet<Map<String, Object>>();
        DataFrame<String, String, Integer> hv = new DataFrame<String, String, Integer>(0);

        for (int q = 0; q <= contig.length() - cg.getKmerSize(); q++) {
          // String sk = cv.getBinaryKmer();
          String sk = contig.substring(q, q + cg.getKmerSize());
          CortexKmer ck = new CortexKmer(sk);

          for (CortexLinksMap link : links) {
            if (link.containsKey(ck)) {
              CortexLinksRecord clr = link.get(ck);
              Map<String, Integer> lc =
                  (!showLinks)
                      ? new HashMap<String, Integer>()
                      : CortexUtils.getKmersAndCoverageInLink(cg, sk, clr);

              Map<String, Object> entry = new HashMap<String, Object>();
              entry.put("kmer", sk);
              entry.put("lc", lc);

              verticesWithLinks.add(entry);

              if (showLinks) {
                for (CortexJunctionsRecord cjr : clr.getJunctions()) {
                  List<String> lk = CortexUtils.getKmersInLink(cg, sk, cjr);

                  for (int i = 0; i < lk.size(); i++) {
                    String kili = lk.get(i);

                    for (int j = 0; j < lk.size(); j++) {
                      String kilj = lk.get(j);

                      if (i != j) {
                        hv.set(kili, kilj, hv.get(kili, kilj) + cjr.getCoverage(0));
                      }
                    }
                  }
                }
              }
            }
          }
        }

        /*
        int hvMax = 0;
        Map<String, Integer> hvlin = new HashMap<String, Integer>();
        if (showLinks) {
            for (String kili : hv.getRowNames()) {
                for (String kilj : hv.getColNames()) {
                    int cov = hv.get(kili, kilj);

                    String id = kili + "_" + kilj;
                    hvlin.put(id, cov);

                    if (cov > hvMax) {
                        hvMax = cov;
                    }
                }
            }
        }
        */

        JSONObject jo = new JSONObject();
        jo.put("contig", contig);
        jo.put("originalContig", originalContig);
        jo.put("ref", refFormattedString);
        jo.put("kmerOrigin", kmerOrigin);
        jo.put("kmerSize", cg.getKmerSize());
        jo.put("clipStart", firstFlank.length());
        jo.put("clipEnd", contig.length() - lastFlank.length());

        List<Map<String, Object>> va = new ArrayList<Map<String, Object>>();
        for (CtxVertex v : g.vertexSet()) {
          Map<String, Object> vm = new HashMap<String, Object>();
          vm.put("base", v.getBase());
          vm.put("kmer", v.getKmer());
          vm.put("pos", v.getPos());
          vm.put("type", v.getVertexType().name());
          vm.put("missing", v.isMissingFromGraph());
          vm.put("cov", v.getCoverage());

          va.add(vm);
        }

        jo.put("vertices", va);
        jo.put("verticesWithLinks", verticesWithLinks);
        // jo.put("hvlin", hvlin);
        // jo.put("hvmax", hvMax);

        return jo.toString();
      }

      return null;
    }