예제 #1
0
 // 生成一个叶子信息
 public Leaf generateLeaf() {
   Leaf leaf = new Leaf();
   int randomType = random.nextInt(3);
   // 随时类型- 随机振幅
   StartType type = StartType.MIDDLE;
   switch (randomType) {
     case 0:
       break;
     case 1:
       type = StartType.LITTLE;
       break;
     case 2:
       type = StartType.BIG;
       break;
     default:
       break;
   }
   leaf.type = type;
   // 随机起始的旋转角度
   leaf.rotateAngle = random.nextInt(360);
   // 随机旋转方向(顺时针或逆时针)
   leaf.rotateDirection = random.nextInt(2);
   // 为了产生交错的感觉,让开始的时间有一定的随机性
   mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
   mAddTime += random.nextInt((int) (mLeafFloatTime * 2));
   leaf.startTime = System.currentTimeMillis() + mAddTime;
   return leaf;
 }
예제 #2
0
 @Override
 public Leaf deserialize(JsonParser jp, DeserializationContext ctxt)
     throws IOException, JsonProcessingException {
   JsonNode tree = (JsonNode) jp.readValueAsTree();
   Leaf leaf = new Leaf();
   leaf.value = tree.get("value").intValue();
   return leaf;
 }
예제 #3
0
 private Component childForNode(Node node) {
   if (node instanceof Leaf) {
     Leaf leaf = (Leaf) node;
     String name = leaf.getName();
     return (name != null) ? childMap.get(name) : null;
   }
   return null;
 }
예제 #4
0
    public boolean stealFromRight(Leaf right) {
      if (right.size() > capacity / 2) {
        append(right.firstKey(), right.firstValue());
        right.removeFirst();
        return true;
      }

      return false;
    }
예제 #5
0
  /** "Return" invokes smart scroll, which closes up current section, and opens next. */
  public boolean eventAfter(AWTEvent e, Point scrn, Node obsn) {
    int eid = e.getID();
    // System.out.println("Outliner eventBefore "+eid+", outActive_="+outActive_);
    if (outActive_ != null
        && outActive_.isSet()
        && outActive_.isOpen() /*always true?*/ /* && outSects_.indexOf(outActive_)==-1*/
        && /*active_ &&*/ eid == KeyEvent.KEY_PRESSED
        && ((KeyEvent) e).getKeyChar() == ' ' // ).getKeyCode()==KeyEvent.VK_ENTER
    ) {
      Browser br = getBrowser();

      // find next
      OutlineSpan next = nextSection(outActive_.getStart().leaf);
      Node outn = outActive_.getStart().leaf;
      IScrollPane isp = outn.getIScrollPane();
      VScrollbar vsb = isp.getVsb();
      int y = vsb.getValue(), h = isp.bbox.height;

      if (next != null) {
        Leaf l = (Leaf) next.getStart().leaf;
        Point rel = l.getRelLocation(isp);

        // if next on screen open next, closing up previous of <= level
        // System.out.println(y+" .. "+l.getNextLeaf()+"/"+rel.y+" .. "+(y+h));
        if (y < rel.y && rel.y < y + h) {
          // close up current and previous while <= level

          int level = Integers.parseInt(next.getAttr(OutlineSpan.ATTR_LEVEL), 1);

          for (OutlineSpan prev = outActive_;
              prev != null;
              prev = prevSection(prev.getStart().leaf)) {
            br.eventq(OutlineSpan.MSG_CLOSE, prev);
            if (Integers.parseInt(prev.getAttr(OutlineSpan.ATTR_LEVEL), Integer.MIN_VALUE) <= level)
              break; // stop after first at same level as next/new current
          }

          outActive_ = next;
          br.eventq(OutlineSpan.MSG_OPEN, outActive_); // includes l.scrollTo(0,0, true);
          // System.out.println("open "+outActive_);
        } // else fall through to scroll
        return true;

      } else if (y + h >= vsb.getMax()) { // at end, just close up
        // System.out.println("couldn't find next OutlineSpan"); -- at end
        br.eventq(OutlineSpan.MSG_CLOSE, outActive_);
        outActive_ = null;
      }

      // close current and open next
      // br.setGrab(this);	// get key release
      // return true;
    }

    return false;
  }
예제 #6
0
    public boolean stealFromLeft(Leaf left) {
      if (left.size() > capacity / 2) {
        push(left.lastKey(), left.lastValue());
        left.clearLast();

        return true;
      }

      return false;
    }
예제 #7
0
    public void mergeFrom(Node right) {
      assert (right.size() == capacity / 2) || (size == capacity / 2)
          : "Should have exactly half capacity nodes";

      Leaf leaf = (Leaf) right;

      shallowCopy(leaf, 0, this, size, leaf.size());
      next = leaf.next();

      size += leaf.size();
    }
예제 #8
0
 /**
  * Starts a query with the given query info by relaying it to an ultrapeer
  *
  * @param info
  */
 public void startQuery(IQueryInfo info, int hitsWanted) {
   Query q = new Query(info);
   owner.getLocalEventDispatcher().queryStarted(owner.getOwnContact(), q);
   Gnutella06OverlayContact peerForQuery = mgr.getRandomContact();
   if (peerForQuery != null) {
     new LeafQueryOperation(owner, q, hitsWanted, peerForQuery, this.new QueryCallback(q))
         .scheduleImmediately();
   } else {
     log.debug("Cannot start query because node " + owner.getOwnContact() + " has no ultrapeer.");
   }
 }
예제 #9
0
  // ------------------------------------------------------
  public void draw() {

    background(255, 240, 240);
    fond.draw();
    branche.draw();

    // branche.drawStructure();
    for (Leaf f : feuilles) f.draw();
    // saveFrame("data/filename-"+minute()+":"+second()+".png");
    noLoop();
  }
예제 #10
0
 public void toString(StringBuffer buf, int tab) {
   for (int i = 0; i < tab; i++) buf.append("|  ");
   if (this instanceof InternalNode) {
     InternalNode in = (InternalNode) this;
     buf.append(in.test + ">=" + in.threshold + ":\n");
     // in.getTrueBranch().toString(buf,tab+1);
     // in.getFalseBranch().toString(buf,tab+1);
   } else {
     Leaf leaf = (Leaf) this;
     buf.append(leaf.getScore() + "\n");
   }
 }
예제 #11
0
 OutlineSpan nextSection(Node after) {
   for (Leaf l = after.getNextLeaf(); l != null; l = l.getNextLeaf()) {
     for (int i = 0, imax = l.sizeSticky(); i < imax; i++) {
       Mark m = l.getSticky(i);
       Object owner = m.getOwner();
       if (owner instanceof OutlineSpan && ((OutlineSpan) owner).getStart() == m) {
         return (OutlineSpan) owner;
         // System.out.println("found next active = "+l.getNextLeaf()+", owner="+owner);
       }
     }
   }
   return null;
 }
예제 #12
0
  private void getLeafLocation(Leaf leaf, long currentTime) {
    long intervalTime = currentTime - leaf.startTime;
    mLeafFloatTime = mLeafFloatTime <= 0 ? LEAF_FLOAT_TIME : mLeafFloatTime;
    if (intervalTime < 0) {
      return;
    } else if (intervalTime > mLeafFloatTime) {
      leaf.startTime = System.currentTimeMillis() + new Random().nextInt((int) mLeafFloatTime);
    }

    float fraction = (float) intervalTime / mLeafFloatTime;
    leaf.x = (int) (mProgressWidth - mProgressWidth * fraction);
    leaf.y = getLocationY(leaf);
  }
예제 #13
0
 OutlineSpan prevSection(Node before) {
   for (Leaf l = before.getPrevLeaf(); l != null; l = l.getPrevLeaf()) {
     for (int i = l.sizeSticky() - 1; i >= 0; i--) { // doesn't matte
       Mark m = l.getSticky(i);
       Object owner = m.getOwner();
       if (owner instanceof OutlineSpan && ((OutlineSpan) owner).getStart() == m) {
         return (OutlineSpan) owner;
         // System.out.println("found next active = "+l.getNextLeaf()+", owner="+owner);
       }
     }
   }
   return null;
 }
예제 #14
0
  public BPlusTree(int nodeSize, Comparator<K> comparator) {
    this.nodeSize = nodeSize;
    this.comparator = comparator;

    firstNode = Leaf.newInstance(nodeSize);
    this.root = firstNode;
  }
예제 #15
0
  /** @param args */
  public static void main(String[] args) {
    // 操作单一方法
    Leaf l = new Leaf();
    l.sampleOperation();

    // 构造根枝
    Composite allc = new Composite();
    // 构造次枝
    Composite c1 = new Composite();
    allc.add(c1);
    // 构造叶子
    c1.add(new Leaf());
    c1.add(new Leaf());
    c1.remove(new Leaf());

    allc.sampleOperation();
  }
예제 #16
0
    @SuppressWarnings("unchecked")
    @Override
    public Map.Entry<K, V> next() {
      if ((index + 1) < leaf.size()) {
        index++;

        Entry entry = leaf.get(index);
        return entry;

      } else if (leaf.next() != null) {
        leaf = leaf.next();
        index = 0;

        Entry entry = leaf.get(index);
        return entry;
      }

      throw new NoSuchElementException();
    }
예제 #17
0
    private void compactLeaves(Leaf node, int index, int nodeOffset) {
      if (index + 1 <= size) {
        Leaf left = node;
        Leaf right = (Leaf) getChild(nodeOffset + 2);

        if (left.stealFromRight(right)) {
          setChild(nodeOffset + 1, right.firstKey());
        } else {
          left.mergeFrom(right);
          removeMergedNode(nodeOffset);
        }
      } else {
        Leaf left = (Leaf) getChild(nodeOffset - 2);
        Leaf right = node;

        if (right.stealFromLeft(left)) {
          setChild(nodeOffset - 1, right.firstKey());
        } else {
          left.mergeFrom(right);
          removeMergedNode(nodeOffset);
        }
      }
    }
예제 #18
0
  /* (non-Javadoc)
   * @see net.sourceforge.arbaro.tree.TreeTraversal#visitLeaf(net.sourceforge.arbaro.tree.Leaf)
   */
  public boolean visitLeaf(Leaf leaf) {
    // prints povray code for the leaf
    String indent = "    ";

    w.println(
        indent
            + "object { "
            + povrayDeclarationPrefix
            + "leaf "
            + transformationStr(leaf.getTransformation())
            + "}");

    //		increment progress count
    exporter.incProgressCount(AbstractExporter.LEAF_PROGRESS_STEP);

    return true;
  }
예제 #19
0
 /**
  * testing leaf
  *
  * @author Sam Whitlock (cs61b-eo)
  * @param void
  * @return void
  */
 @Test
 public void leafTest1() {
   QuadPoint qp = new QuadPoint(13, 19);
   Leaf<QuadTree.QuadPoint> myPt = new Leaf<QuadTree.QuadPoint>(qp, null, null);
   assertTrue(myPt.x() == 13);
   assertTrue(myPt.y() == 19);
   assertEquals(qp, myPt.leaf);
   LeafNode<QuadPoint> lfnd = new LeafNode<QuadPoint>(null, null, 0, 0, 100, 100);
   myPt.parent = lfnd;
   assertEquals(myPt.parent = lfnd);
   QuadTree<QuadPoint> tree = new QuadTree<QuadPoint>(0, 0, 100, 100, .01);
   myPt.tree = tree;
   assertEquals(myPt.tree, tree);
 }
예제 #20
0
파일: Fog.java 프로젝트: miho/ExtJ3D
  /**
   * Copies all Fog information from <code>originalNode</code> into the current node. This method is
   * called from the <code>cloneNode</code> method which is, in turn, called by the <code>cloneTree
   * </code> method.
   *
   * <p>
   *
   * @param originalNode the original node to duplicate.
   * @param forceDuplicate when set to <code>true</code>, causes the <code>duplicateOnCloneTree
   *     </code> flag to be ignored. When <code>false</code>, the value of each node's <code>
   *     duplicateOnCloneTree</code> variable determines whether NodeComponent data is duplicated or
   *     copied.
   * @exception RestrictedAccessException if this object is part of a live or compiled scenegraph.
   * @see Node#duplicateNode
   * @see Node#cloneTree
   * @see NodeComponent#setDuplicateOnCloneTree
   */
  @Override
  void duplicateAttributes(Node originalNode, boolean forceDuplicate) {
    super.duplicateAttributes(originalNode, forceDuplicate);

    FogRetained attr = (FogRetained) originalNode.retained;
    FogRetained rt = (FogRetained) retained;

    Color3f c = new Color3f();
    attr.getColor(c);
    rt.initColor(c);
    rt.initInfluencingBounds(attr.getInfluencingBounds());

    Enumeration<Group> elm = attr.getAllScopes();
    while (elm.hasMoreElements()) {
      // this reference will set correctly in updateNodeReferences() callback
      rt.initAddScope(elm.nextElement());
    }

    // this reference will set correctly in updateNodeReferences() callback
    rt.initInfluencingBoundingLeaf(attr.getInfluencingBoundingLeaf());
  }
예제 #21
0
파일: Node.java 프로젝트: aniketisin/INCAR
  /**
   * @param bspt
   * @param level
   * @param leafLeft
   * @j2sIgnoreSuperConstructor
   */
  Node(Bspt bspt, int level, Leaf leafLeft) {
    this.bspt = bspt;
    if (level == bspt.treeDepth) {
      bspt.treeDepth = level + 1;
      // no longer necessary  -- in a long unfolded protein,
      // we can go over 100 here
      // if (bspt.treeDepth >= Bspt.MAX_TREE_DEPTH)
      // Logger.error("BSPT tree depth too great:" + bspt.treeDepth);
    }
    if (leafLeft.count != Bspt.leafCountMax) throw new NullPointerException();
    dim = level % bspt.dimMax;
    leafLeft.sort(dim);
    Leaf leafRight = new Leaf(bspt, leafLeft, Bspt.leafCountMax / 2);
    minLeft = getDimensionValue(leafLeft.tuples[0], dim);
    maxLeft = getDimensionValue(leafLeft.tuples[leafLeft.count - 1], dim);
    minRight = getDimensionValue(leafRight.tuples[0], dim);
    maxRight = getDimensionValue(leafRight.tuples[leafRight.count - 1], dim);

    eleLeft = leafLeft;
    eleRight = leafRight;
    count = Bspt.leafCountMax;
  }
예제 #22
0
 private static void parseAttribute(String name, StreamTokenizer st, Node node) throws Exception {
   if ((st.nextToken() != '=')) {
     throwParseException(st, "expected '=' after " + name);
   }
   if (name.equalsIgnoreCase("WEIGHT")) {
     if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
       node.setWeight(st.nval);
     } else {
       throwParseException(st, "invalid weight");
     }
   } else if (name.equalsIgnoreCase("NAME")) {
     if (st.nextToken() == StreamTokenizer.TT_WORD) {
       if (node instanceof Leaf) {
         ((Leaf) node).setName(st.sval);
       } else {
         throwParseException(st, "can't specify name for " + node);
       }
     } else {
       throwParseException(st, "invalid name");
     }
   } else {
     throwParseException(st, "unrecognized attribute \"" + name + "\"");
   }
 }
예제 #23
0
    public Object put(Comparator comparator, Object key, Object val) {
      Object oldVal;

      int search = binarySearch(this, 0, size, key, comparator);
      if (search > -1) {
        Entry entry = get(search);
        oldVal = entry.getValue();
        entry.setValue(val);
      } else if (size < capacity) {
        oldVal = null;

        search = -(search + 1);
        insert(search, key, val);

      } else {
        Leaf next = Leaf.newInstance(capacity);

        int halfSize = size / 2;

        shallowCopy(this, halfSize, next, 0, halfSize);
        clear(halfSize, size);

        size = halfSize;
        next.size = halfSize;

        if (compare(comparator, key, next.firstKey()) < 0) {
          put(comparator, key, val);
        } else {
          next.put(comparator, key, val);
        }

        next.next = this.next;
        this.next = next;

        oldVal = Node.Sentinal.SPLIT;
      }

      return oldVal;
    }
예제 #24
0
파일: Leaf.java 프로젝트: szhang1/TIJ4-code
 public static void main(String[] args) {
   Leaf x = new Leaf();
   x.increment().increment().increment().print();
 }
예제 #25
0
 public GroupId getGroupId(Leaf leaf) {
   if (!groupIds.containsKey(leaf.getDeviceId())) {
     this.initiateGroup(leaf);
   }
   return groupIds.get(leaf.getDeviceId());
 }
예제 #26
0
 @Override
 public boolean hasNext() {
   return (index + 1) < leaf.size() || leaf.next() != null;
 }
예제 #27
0
  /**
   * Dump leaves by direct record scan from first leaf offset until end of leaves region.
   *
   * <p>Note: While this could be rewritten for cleaner code to use {@link
   * IndexSegment#leafIterator(boolean)} but it would make it harder to spot problems in the data.
   *
   * @param store
   */
  static void dumpLeavesForwardScan(final IndexSegmentStore store, final boolean dumpLeafState) {

    final long begin = System.currentTimeMillis();

    final AbstractBTree btree = store.loadIndexSegment();

    // first the address of the first leaf in a left-to-right scan (always defined).
    long addr = store.getCheckpoint().addrFirstLeaf;

    {
      final long addr2 = getFirstLeafAddr(store, store.getCheckpoint().addrRoot);

      if (addr != addr2) {

        log.error(
            "First leaf address is inconsistent? checkpoint reports: "
                + addr
                + " ("
                + store.toString(addr)
                + ")"
                + ", but node hierarchy reports "
                + addr2
                + " ("
                + store.toString(addr2)
                + ")");
      }
    }

    System.out.println("firstLeafAddr=" + store.toString(addr));

    int nscanned = 0;

    while (true) {

      if (!store.getAddressManager().isLeafAddr(addr)) {

        log.error("Not a leaf address: " + store.toString(addr) + " : aborting scan");

        // abort scan.
        break;
      }

      // lower level read
      final ByteBuffer data = store.read(addr);

      // note: does NOT set the parent reference on the Leaf!
      final Leaf leaf = (Leaf) decode(btree, addr, data);

      if (dumpLeafState) leaf.dump(System.out);

      nscanned++;

      final long nextAddr = ((ImmutableLeaf) leaf).getNextAddr();

      if (nextAddr == -1L) {

        log.error(
            "Expecting the next address to be known - aborting scan: current addr="
                + addr
                + " ("
                + store.toString(addr)
                + ")");

        // abort scan.
        break;
      }

      if (nextAddr == 0L) {

        if (nscanned != store.getCheckpoint().nleaves) {

          log.error(
              "Scanned "
                  + nscanned
                  + " leaves, but checkpoint record indicates that there are "
                  + store.getCheckpoint().nleaves
                  + " leaves");
        }

        // Done (normal completion).
        break;
      }

      addr = nextAddr;
    }

    final long elapsed = System.currentTimeMillis() - begin;

    System.out.println(
        "Visited " + nscanned + " leaves using fast forward scan in " + elapsed + " ms");
  }