Ejemplo n.º 1
0
 private int totalSize(List<Segment> unsortedSegments) {
   int totalSize = 0;
   for (Segment segment : unsortedSegments) {
     totalSize += segment.length();
   }
   return totalSize;
 }
Ejemplo n.º 2
0
 private static Point2D intersect(KDNode node, Segment seg) {
   if (node.isLeaf()) {
     // long begin = System.nanoTime();
     Intersection min = null;
     for (TriangleRef r : node.refs) {
       // inters++;
       Intersection i = seg.intersectTriangle(r.triangle);
       if (i != null) {
         if (min == null || min.getDistance() > i.getDistance()) {
           min = i;
         }
       }
     }
     // interTime += System.nanoTime()-begin;
     return min == null ? null : min.getIntersection();
   } else {
     // recursion++;
     boolean splitAtX = node.splittingPlane.dimension == Dimension.X;
     double splitValue = node.splittingPlane.splitValue;
     return seg.splitAtXorY(splitAtX, splitValue)
         .map(
             (startOnLeftSide, start, end) -> {
               if (startOnLeftSide) {
                 Point2D p = intersect(node.left, start);
                 return p != null || end == null ? p : intersect(node.right, end);
               } else {
                 Point2D p = intersect(node.right, start);
                 return p != null || end == null ? p : intersect(node.left, end);
               }
             });
   }
 }
Ejemplo n.º 3
0
  @Override
  @Nullable
  public PsiElement restoreElement() {
    long typeAndId = myStubElementTypeAndId;
    int stubId = (int) typeAndId;
    if (stubId != -1) {
      PsiFile file = restoreFile();
      if (!(file instanceof PsiFileWithStubSupport)) return null;
      short index = (short) (typeAndId >> 32);
      IStubElementType stubElementType = (IStubElementType) IElementType.find(index);
      return PsiAnchor.restoreFromStubIndex(
          (PsiFileWithStubSupport) file, stubId, stubElementType, false);
    }

    Segment psiRange = getPsiRange();
    if (psiRange == null) return null;

    PsiFile file = restoreFile();
    if (file == null) return null;
    PsiElement anchor = file.findElementAt(psiRange.getStartOffset());
    if (anchor == null) return null;

    TextRange range = anchor.getTextRange();
    if (range.getStartOffset() != psiRange.getStartOffset()
        || range.getEndOffset() != psiRange.getEndOffset()) return null;

    for (SmartPointerAnchorProvider provider : SmartPointerAnchorProvider.EP_NAME.getExtensions()) {
      final PsiElement element = provider.restoreElement(anchor);
      if (element != null) return element;
    }
    return null;
  }
Ejemplo n.º 4
0
 /**
  * Takes a {@link java.lang.String} representation of segment, creates a {@link Segment} object
  * and adds the segment to the current Loop.
  *
  * @param segment {@link java.lang.String} representation of the Segment.
  * @return a new Segment object
  */
 public Segment addSegment(String segment) {
   Segment s = new Segment(this.context);
   String[] elements = segment.split("\\" + context.getElementSeparator());
   s.addElements(elements);
   segments.add(s);
   return s;
 }
Ejemplo n.º 5
0
          public int compare(Segment<K, V> o1, Segment<K, V> o2) {
            if (o1.getLength() == o2.getLength()) {
              return 0;
            }

            return o1.getLength() < o2.getLength() ? -1 : 1;
          }
Ejemplo n.º 6
0
  /**
   * Write the cluster and the segments to a CTL \e *FILE.
   *
   * @param dos the DataOutPutstream to write to
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void writeAsCTL(OutputStreamWriter dos) throws IOException {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    DecimalFormat df = new DecimalFormat();
    df.setDecimalFormatSymbols(dfs);
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);
    df.setGroupingUsed(false);

    for (Segment seg : segmentSet) {
      float start = seg.getStartInSecond();
      float end = seg.getEndInSecond();
      String band = Segment.bandwidthNistStrings[0];
      if (seg.getBandwidth() == Segment.bandwidthStrings[1]) {
        band = Segment.bandwidthNistStrings[1];
      } else if (seg.getBandwidth() == Segment.bandwidthStrings[2]) {
        band = Segment.bandwidthNistStrings[2];
      }

      String line =
          seg.getShowName() + " " + seg.getStart() + " " + (seg.getStart() + seg.getLength());
      line += " " + seg.getShowName() + "-" + df.format(start) + "-" + df.format(end) + "-" + band;
      line += "-" + this.gender + "-" + name + "\n";
      dos.write(line);
    }
  }
Ejemplo n.º 7
0
  /**
   * Write as eger.
   *
   * @param dos the dos
   * @param type the type
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public void writeAsEGER(OutputStreamWriter dos, String type) throws IOException {
    String line;
    String nameEN;
    for (Segment segment : segmentSet) {
      if (type.equals("writing")) {
        EntitySet entitySet = segment.getTranscription().getEntitySet();
        for (Entity entity : entitySet) {
          // logger.info("WRITING entity : "+entity.getListOfWords());
          if (entity.isPerson()) {
            nameEN = SpeakerNameUtils.normalizeSpeakerName(entity.getListOfWords());
            line = segment.getShowName();
            line += " " + segment.getStartInSecond();
            line += " " + segment.getLastInSecond();
            line += " written";
            line += " " + nameEN + "\n";
            if (segment.getLength() > 0) {
              dos.write(line);
            }
          }
        }

      } else {
        line = segment.getShowName();
        line += " " + segment.getStartInSecond();
        line += " " + segment.getLastInSecond();
        line += " " + type;
        line += " " + name + "\n";
        if (segment.getLength() > 0) {
          dos.write(line);
        }
      }
    }
  }
Ejemplo n.º 8
0
  /**
   * Creates a deep copy of the cluster: segments in the new cluster are copies of the original
   * segments, not references.
   *
   * @return the object
   */
  @Override
  public Cluster clone() {
    Cluster result = null;
    try {
      result = (Cluster) (super.clone());
    } catch (CloneNotSupportedException e) {
      logger.log(Level.SEVERE, "", e);
      e.printStackTrace();
    }
    result.segmentSet = new TreeSet<Segment>();
    for (Segment segment : segmentSet) {
      result.segmentSet.add((segment.clone()));
    }
    result.informationMap = new TreeMap<String, Object>(new StringComparator());
    for (String key : informationMap.keySet()) {
      result.setInformation(key, informationMap.get(key));
    }

    result.modelScores = new ModelScores();
    for (String key : modelScores.keySet()) {
      result.modelScores.put(key, modelScores.get(key));
    }

    result.speakerNameSet = (SpeakerNameSet) speakerNameSet.clone();

    return result;
  }
Ejemplo n.º 9
0
 /**
  * Gets the sum of the segment lengths.
  *
  * @return the length sum
  */
 public int getLength() {
   int length = 0;
   for (Segment segment : segmentSet) {
     length += segment.getLength();
   }
   return length;
 }
Ejemplo n.º 10
0
 private List<Segment> getAllSegmentDefinitions() {
   List<Segment> allItems = persistenceService.getAllItems(Segment.class);
   for (Segment segment : allItems) {
     ParserHelper.resolveConditionType(definitionsService, segment.getCondition());
   }
   return allItems;
 }
Ejemplo n.º 11
0
 public Segment getSegmentDefinition(String segmentId) {
   Segment definition = persistenceService.load(segmentId, Segment.class);
   if (definition != null) {
     ParserHelper.resolveConditionType(definitionsService, definition.getCondition());
   }
   return definition;
 }
Ejemplo n.º 12
0
 /**
  * Get the list of keys. This method allows to read the internal state of the cache.
  *
  * @param cold if true, only keys for the cold entries are returned
  * @param nonResident true for non-resident entries
  * @return the key list
  */
 public List<Long> keys(boolean cold, boolean nonResident) {
   ArrayList<Long> keys = new ArrayList<Long>();
   for (Segment<V> s : segments) {
     keys.addAll(s.keys(cold, nonResident));
   }
   return keys;
 }
Ejemplo n.º 13
0
 /**
  * Get the set of keys for resident entries.
  *
  * @return the set of keys
  */
 public Set<Long> keySet() {
   HashSet<Long> set = new HashSet<Long>();
   for (Segment<V> s : segments) {
     set.addAll(s.keySet());
   }
   return set;
 }
Ejemplo n.º 14
0
  /**
   * Method description
   *
   * @param heading
   * @return
   */
  public List<LocusScore> getWholeGenomeScores(String heading) {

    List<LocusScore> wholeGenomeScores = wholeGenomeScoresCache.get(heading);
    if ((wholeGenomeScores == null) || wholeGenomeScores.isEmpty()) {
      int locationUnit = 1000;

      // Compute the smallest concievable feature that could be viewed on the
      // largest screen.  Be conservative.   The smallest feature is one at
      // the screen resolution scale in <chr units> / <pixel>
      int maxScreenSize = 4000;
      double minFeatureSize = 0; // ((double) genome.getLength()) / (maxScreenSize * locationUnit);

      long offset = 0;
      wholeGenomeScores = new ArrayList(1000);
      for (String chr : genome.getChromosomeNames()) {
        List<LocusScore> chrSegments = getSegments(heading, chr);
        if (chrSegments != null) {
          int lastgEnd = -1;
          for (LocusScore score : chrSegments) {
            Segment seg = (Segment) score;
            int gStart = (int) ((offset + score.getStart()) / locationUnit);
            int gEnd = (int) ((offset + score.getEnd()) / locationUnit);
            if ((gEnd - gStart) > minFeatureSize) {
              wholeGenomeScores.add(
                  new Segment(gStart, gStart, gEnd, gEnd, seg.getScore(), seg.getDescription()));
            }
          }
        }
        offset += genome.getChromosome(chr).getLength();
      }
      wholeGenomeScoresCache.put(heading, wholeGenomeScores);
    }
    return wholeGenomeScores;
  }
 @Override
 public boolean isEmpty() {
   for (Segment<K, V> segment : segments) {
     if (segment.size() > 0) return false;
   }
   return true;
 }
Ejemplo n.º 16
0
 private void initGuardedBlocks(Place shreds) {
   int origOffset = -1;
   int curOffset = 0;
   for (PsiLanguageInjectionHost.Shred shred : shreds) {
     Segment hostRangeMarker = shred.getHostRangeMarker();
     int start = shred.getRange().getStartOffset() + shred.getPrefix().length();
     int end = shred.getRange().getEndOffset() - shred.getSuffix().length();
     if (curOffset < start) {
       RangeMarker guard = myNewDocument.createGuardedBlock(curOffset, start);
       if (curOffset == 0 && shred == shreds.get(0)) guard.setGreedyToLeft(true);
       String padding =
           origOffset < 0
               ? ""
               : myOrigDocument.getText().substring(origOffset, hostRangeMarker.getStartOffset());
       guard.putUserData(REPLACEMENT_KEY, fixQuotes(padding));
     }
     curOffset = end;
     origOffset = hostRangeMarker.getEndOffset();
   }
   if (curOffset < myNewDocument.getTextLength()) {
     RangeMarker guard =
         myNewDocument.createGuardedBlock(curOffset, myNewDocument.getTextLength());
     guard.setGreedyToRight(true);
     guard.putUserData(REPLACEMENT_KEY, "");
   }
 }
  public char[] increaseFreeSpace(/*int size*/ char[] buffer) {
    int size = buffer.length; // double size of buffer

    // increase buffer
    buffer = Arrays.copyOf(buffer, buffer.length * 2);

    // actual suspended location
    if (suspendedLength > 0) {
      int suspendedOffset = suspendedSegments.peekLast().start;

      // move suspended data to the end of the buffer
      System.arraycopy(
          buffer, suspendedOffset, buffer, buffer.length - suspendedLength, suspendedLength);
    }

    this.freeLength += size;
    this.size += size;

    for (Iterator<Segment<T>> it = suspendedSegments.iterator(); it.hasNext(); ) {
      Segment<T> segment = it.next();
      segment.start += size;
    }

    return buffer;
  }
 static <T> Segment<T> newSegment(T source, int start, int length) {
   Segment segment = new Segment();
   segment.source = source;
   segment.start = start;
   segment.length = length;
   return segment;
 }
Ejemplo n.º 19
0
 /* (non-Javadoc)
  * @see org.dyn4j.geometry.Shape#contains(org.dyn4j.geometry.Vector, org.dyn4j.geometry.Transform)
  */
 @Override
 public boolean contains(Vector2 point, Transform transform) {
   // if the polygon is convex then do a simple inside test
   // if the the sign of the location of the point on the side of an edge (or line)
   // is always the same and the polygon is convex then we know that the
   // point lies inside the polygon
   // This method doesn't care about vertex winding
   // inverse transform the point to put it in local coordinates
   Vector2 p = transform.getInverseTransformed(point);
   Vector2 p1 = this.vertices[0];
   Vector2 p2 = this.vertices[1];
   // get the location of the point relative to the first two vertices
   double last = Segment.getLocation(p, p1, p2);
   int size = this.vertices.length;
   // loop through the rest of the vertices
   for (int i = 1; i < size; i++) {
     // p1 is now p2
     p1 = p2;
     // p2 is the next point
     p2 = this.vertices[(i + 1) == size ? 0 : i + 1];
     // check if they are equal (one of the vertices)
     if (p.equals(p1)) {
       return true;
     }
     // do side of line test
     // multiply the last location with this location
     // if they are the same sign then the opertation will yield a positive result
     // -x * -y = +xy, x * y = +xy, -x * y = -xy, x * -y = -xy
     if (last * Segment.getLocation(p, p1, p2) < 0) {
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 20
0
 @Override
 public Map<String, Integer> getPermissions(Set<Entry<String, String>> set) {
   final Segment entry = this.segments.get(set);
   return entry == null || entry.getPermissions() == null
       ? Collections.emptyMap()
       : entry.getPermissions();
 }
Ejemplo n.º 21
0
 @Override
 public List<Entry<String, String>> getParents(Set<Entry<String, String>> segments) {
   Segment ent = this.segments.get(segments);
   return ent == null || ent.getParents() == null
       ? Collections.emptyList()
       : ImmutableList.copyOf(ent.getParents());
 }
 public Virtual8086ModeSegment(AddressSpace memory, Segment ancestor) {
   super(memory, true);
   selector = ancestor.getSelector();
   base = ancestor.getBase();
   type = ancestor.getType();
   limit = 0xffffffffL & ancestor.getLimit();
 }
 @Override
 @Deprecated
 @Nullable
 public TextRange intersectWithEditable(@NotNull TextRange rangeToEdit) {
   int startOffset = -1;
   int endOffset = -1;
   synchronized (myLock) {
     int offset = 0;
     for (PsiLanguageInjectionHost.Shred shred : myShreds) {
       Segment hostRange = shred.getHostRangeMarker();
       if (hostRange == null) continue;
       offset += shred.getPrefix().length();
       int length = hostRange.getEndOffset() - hostRange.getStartOffset();
       TextRange intersection =
           new ProperTextRange(offset, offset + length).intersection(rangeToEdit);
       if (intersection != null) {
         if (startOffset == -1) {
           startOffset = intersection.getStartOffset();
         }
         endOffset = intersection.getEndOffset();
       }
       offset += length;
       offset += shred.getSuffix().length();
     }
   }
   if (startOffset == -1) return null;
   return new ProperTextRange(startOffset, endOffset);
 }
  @Nullable("null means we were unable to calculate")
  LogicalPosition hostToInjectedInVirtualSpace(@NotNull LogicalPosition hPos) {
    // beware the virtual space
    int hLineStartOffset =
        hPos.line >= myDelegate.getLineCount()
            ? myDelegate.getTextLength()
            : myDelegate.getLineStartOffset(hPos.line);
    int iLineStartOffset = hostToInjected(hLineStartOffset);
    int iLine = getLineNumber(iLineStartOffset);

    synchronized (myLock) {
      for (int i = myShreds.size() - 1; i >= 0; i--) {
        PsiLanguageInjectionHost.Shred shred = myShreds.get(i);
        if (!shred.isValid()) continue;
        Segment hostRangeMarker = shred.getHostRangeMarker();
        if (hostRangeMarker == null) continue;
        int hShredEndOffset = hostRangeMarker.getEndOffset();
        int hShredStartOffset = hostRangeMarker.getStartOffset();

        int hShredStartLine = myDelegate.getLineNumber(hShredStartOffset);
        int hShredEndLine = myDelegate.getLineNumber(hShredEndOffset);

        if (hShredStartLine <= hPos.line && hPos.line <= hShredEndLine) {
          int hColumnOfShredEnd = hShredEndOffset - hLineStartOffset;
          int iColumnOfShredEnd = hostToInjected(hShredEndOffset) - iLineStartOffset;
          int iColumn = iColumnOfShredEnd + hPos.column - hColumnOfShredEnd;
          return new LogicalPosition(iLine, iColumn);
        }
      }
    }

    return null;
  }
  @Override
  public int getLineStartOffset(int line) {
    LOG.assertTrue(line >= 0, line);
    if (line == 0) return 0;
    String hostText = myDelegate.getText();

    int[] pos = new int[2]; // pos[0] = curLine; pos[1] == offset;
    synchronized (myLock) {
      for (PsiLanguageInjectionHost.Shred shred : myShreds) {
        Segment hostRange = shred.getHostRangeMarker();
        if (hostRange == null) continue;

        int found = countNewLinesIn(shred.getPrefix(), pos, line);
        if (found != -1) return found;

        CharSequence text =
            hostText.subSequence(hostRange.getStartOffset(), hostRange.getEndOffset());
        found = countNewLinesIn(text, pos, line);
        if (found != -1) return found;

        found = countNewLinesIn(shred.getSuffix(), pos, line);
        if (found != -1) return found;
      }
    }

    return pos[1];
  }
  public void reset(int pos, char[] buffer) {
    if (pos < 0 && activeSegments.size() == 1) {
      return;
    }

    while (true) {
      Segment<T> lastActiveSegment = activeSegments.peekLast();
      if (pos < lastActiveSegment.start - 1) {
        // segment is removed if root, and last suspended segment is merged
        // with last active segment if it is the same source
        if (lastActiveSegment.root) {
          activeSegments.removeLast();
          activeLength -= lastActiveSegment.length;
          freeLength += lastActiveSegment.length;

          lastActiveSegment = activeSegments.peekLast();
          Segment<T> lastSuspendedSegment = suspendedSegments.peekLast();
          if (lastSuspendedSegment != null
              && lastSuspendedSegment.source.equals(lastActiveSegment.source)) {
            lastActiveSegment.length += lastSuspendedSegment.length;

            // move data in buffer : suspended space -> active space
            System.arraycopy(
                buffer,
                lastSuspendedSegment.start,
                buffer,
                activeLength,
                lastSuspendedSegment.length);

            suspendedSegments.removeLast();
            activeLength += lastSuspendedSegment.length;
            suspendedLength -= lastSuspendedSegment.length;
          }

          continue;
        }

        // segment is suspended if not root
        activeSegments.removeLast();
        suspendedSegments.addLast(lastActiveSegment);
        int startInSuspendedSpace = size - suspendedLength - lastActiveSegment.length;

        // move data in buffer : active space -> suspended space
        System.arraycopy(
            buffer,
            lastActiveSegment.start,
            buffer,
            startInSuspendedSpace,
            lastActiveSegment.length);
        lastActiveSegment.start = startInSuspendedSpace;

        activeLength -= lastActiveSegment.length;
        suspendedLength += lastActiveSegment.length;

      } else {
        break;
      }
    }
  }
Ejemplo n.º 27
0
 /**
  * Copies the specified substring of the document into a segment. If the offsets are invalid, the
  * segment will contain a null string.
  *
  * @param start The start offset
  * @param len The length of the substring
  * @param segment The segment
  */
 public final void getText(int start, int len, Segment segment) {
   try {
     document.getText(start, len, segment);
   } catch (BadLocationException bl) {
     bl.printStackTrace();
     segment.offset = segment.count = 0;
   }
 }
Ejemplo n.º 28
0
 public void addVariable(DapVariable var, List<Slice> slices) throws DapException {
   if (findVariableIndex(var) < 0) {
     Segment segment = new Segment(var);
     segment.setSlices(slices);
     this.segments.add(segment);
     this.variables.add(var);
   }
 }
Ejemplo n.º 29
0
  public static Segment shallowCopy(Segment segment, Factory factory) {
    Segment clone = factory.newSegment();
    for (String key : segment.keys()) {
      clone.setAttribute(key, segment.getAttribute(key));
    }

    return clone;
  }
 @Override
 public long offHeapUsed() {
   long total = 0;
   for (Segment<K, V> segment : segments) {
     total += segment.offHeapUsed();
   }
   return total;
 }