public void add(int value) { Tree temp = new Tree(); Tree temp2 = new Tree(); int i = 0; if (!isEmpty()) { while (temp != null) { if (compareTo(temp) == 1) { if (temp.right != null) { temp2 = temp; temp = temp.right; } else { break; } } if (compareTo(temp) == -1) { if (temp.left != null) { temp2 = temp; temp = temp.left; } else { break; } } i++; } temp.value = value; temp.parent = temp2; } if (i > length) { length++; } }
@Override public List<List<Node<String>>> search() { boolean canStart = checkWords(wordsPair); canStart &= checkDictionary(dictionary); if (!canStart) { return null; } Tree.Node<String> root = new Tree.Node<>(); root.setData(wordsPair[0]); Tree<String> tree = new Tree<>(); tree.setRootElement(root); String word = root.getItem(); dictionary.remove(word); Node<String> currentNode = root; List<Node<String>> nodes = new ArrayList<>(); while (!word.equals(wordsPair[1]) && currentNode != null) { // потенциальные слова List<String> words = generateCandidates(word); // отсекаем слова, которых нет в словаре for (Iterator<String> iterator = words.iterator(); iterator.hasNext(); ) { String s = iterator.next(); if (!dictionary.contains(s)) { iterator.remove(); } } // удаляем полученные слова из словаря (для исключения цикличности поиска) for (String c : words) { if (!c.equals(wordsPair[1])) { dictionary.remove(c); } } // формируем очередной уровень дерева for (String c : words) { Node<String> n = new Node<>(c); currentNode.addChild(n); if (c.equals(wordsPair[1])) { nodes.add(n); } } currentNode = tree.getNextElement(currentNode, !nodes.isEmpty()); if (currentNode != null) { word = currentNode.getItem(); } else if (nodes.isEmpty()) { return null; } } return tree.getPaths(nodes); }
public final void reset() { last_lit = 0; extra_bits = 0; literalTree.reset(); distTree.reset(); blTree.reset(); }
private static <T> void writeTreeBranch( Tree<T> tree, Writer writer, List<Boolean> lines, boolean lastBranch) throws IOException { for (boolean line : lines) { if (line) { writer.write(" | "); } else { writer.write(" "); } } if (lastBranch) { writer.write(" '-- "); } else { writer.write(" |-- "); } writer.write(String.valueOf(tree.getNodeData())); writer.write("\n"); Iterator<Tree<T>> branchIt = tree.iterator(); while (branchIt.hasNext()) { Tree<T> branch = branchIt.next(); List<Boolean> newLines = new ArrayList<Boolean>(); newLines.addAll(lines); newLines.add(!lastBranch); writeTreeBranch(branch, writer, newLines, !branchIt.hasNext()); } }
/** * Adds a window to the frame container. * * @param parent Parent node * @param window Window to add */ public void addWindow(final MutableTreeNode parent, final TextFrame window) { UIUtilities.invokeAndWait( () -> { final NodeLabel label = new NodeLabel(window, iconManager); eventBus.subscribe(label); swingEventBus.subscribe(label); final TreeViewNode node = new TreeViewNode(label, window); synchronized (nodes) { nodes.put(window, node); } if (parent == null) { model.insertNodeInto(node, model.getRootNode()); } else { model.insertNodeInto(node, parent); } tree.expandPath(new TreePath(node.getPath()).getParentPath()); final Rectangle view = tree.getRowBounds(tree.getRowForPath(new TreePath(node.getPath()))); if (view != null) { tree.scrollRectToVisible(new Rectangle(0, (int) view.getY(), 0, 0)); } node.getLabel() .unreadStatusChanged( new UnreadStatusChangedEvent( window.getContainer(), window.getContainer().getUnreadStatusManager(), window.getContainer().getUnreadStatusManager().getNotificationColour(), window.getContainer().getUnreadStatusManager().getUnreadLines())); node.getLabel() .iconChanged( new FrameIconChangedEvent( window.getContainer(), window.getContainer().getIcon())); }); }
/** Unit tests */ public static void main(String[] args) { final Tree targetTree = tree( 1, tree( 2, tree(3, tree(4), tree(3, tree(4), tree(5))), tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree()))), tree(12)); System.out.println(" Test Pattern"); checkPattern(targetTree, tree(), Optional.of(targetTree)); checkPattern(targetTree, tree(9), Optional.of(tree(9))); checkPattern(targetTree, tree(12), Optional.of(tree(12))); checkPattern(targetTree, tree(13), Optional.empty()); checkPattern(targetTree, tree(1), Optional.of(targetTree)); checkPattern(targetTree, tree(2, tree(3), tree(5)), Optional.of(targetTree.left())); checkPattern( targetTree, tree(3, tree(4), tree(5)), Optional.of(targetTree.left().left().right())); checkPattern( targetTree, tree(6, tree(), tree(8)), Optional.of(targetTree.left().right().left())); checkPattern(targetTree, tree(6, tree(), tree(7)), Optional.empty()); checkPattern( targetTree, tree(5, tree(6, tree(7), tree(8, tree(9), tree())), tree(10, tree(11), tree())), Optional.of(targetTree.left().right())); }
/** * Function to print the tree. * * @param depth Depth of the node in the tree. * @param text The tree. */ private void printTree(int depth, StringBuffer text) { String aux = ""; String aux2 = ""; for (int k = 0; k < depth - 1; k++) { aux += "\t"; } for (int k = 0; k < depth; k++) { aux2 += "\t"; } text.append(aux2); if (nodo.isLeaf) { // text.append(nodo.printString() + " ["+indiceNodoT+"]\n"); text.append(nodo.printString() + " \n"); } else if (nodo != null) { /*text.append("[" + indiceNodo + "/" + marcado + "] if ( " + nodo.printString() + " ) then{\n");*/ if (hijoI != null) { text.append("if ( " + nodo.printString() + " ) then{\n"); hijoI.printTree(depth + 1, text); } if (hijoD != null) { text.append(aux2 + "else{ \n"); hijoD.printTree(depth + 1, text); } } text.append(aux + "}\n"); }
static TreeItem NextItem(Tree tree, TreeItem item) { if (item == null) return null; if (item.getExpanded()) { return item.getItem(0); } else { TreeItem childItem = item; TreeItem parentItem = childItem.getParentItem(); int index = parentItem == null ? tree.indexOf(childItem) : parentItem.indexOf(childItem); int count = parentItem == null ? tree.getItemCount() : parentItem.getItemCount(); while (true) { if (index + 1 < count) { return parentItem == null ? tree.getItem(index + 1) : parentItem.getItem(index + 1); } else { if (parentItem == null) { return null; } else { childItem = parentItem; parentItem = childItem.getParentItem(); index = parentItem == null ? tree.indexOf(childItem) : parentItem.indexOf(childItem); count = parentItem == null ? tree.getItemCount() : parentItem.getItemCount(); } } } } }
/** * Attempts to retrieve the specified tree rule from storage. * * @param tsdb The TSDB to use for storage access * @param tree_id ID of the tree the rule belongs to * @param level Level where the rule resides * @param order Order where the rule resides * @return A TreeRule object if found, null if it does not exist * @throws HBaseException if there was an issue * @throws IllegalArgumentException if the one of the required parameters was missing * @throws JSONException if the object could not be serialized */ public static Deferred<TreeRule> fetchRule( final TSDB tsdb, final int tree_id, final int level, final int order) { if (tree_id < 1 || tree_id > 65535) { throw new IllegalArgumentException("Invalid Tree ID"); } if (level < 0) { throw new IllegalArgumentException("Invalid rule level"); } if (order < 0) { throw new IllegalArgumentException("Invalid rule order"); } // fetch the whole row final GetRequest get = new GetRequest(tsdb.treeTable(), Tree.idToBytes(tree_id)); get.family(Tree.TREE_FAMILY()); get.qualifier(getQualifier(level, order)); /** Called after fetching to parse the results */ final class FetchCB implements Callback<Deferred<TreeRule>, ArrayList<KeyValue>> { @Override public Deferred<TreeRule> call(final ArrayList<KeyValue> row) { if (row == null || row.isEmpty()) { return Deferred.fromResult(null); } return Deferred.fromResult(parseFromStorage(row.get(0))); } } return tsdb.getClient().get(get).addCallbackDeferring(new FetchCB()); }
public static void main(String[] args) { QPTreeTransformer transformer = new QPTreeTransformer(); Treebank tb = new MemoryTreebank(); Properties props = StringUtils.argsToProperties(args); String treeFileName = props.getProperty("treeFile"); if (treeFileName != null) { try { TreeReader tr = new PennTreeReader( new BufferedReader(new InputStreamReader(new FileInputStream(treeFileName))), new LabeledScoredTreeFactory()); Tree t; while ((t = tr.readTree()) != null) { tb.add(t); } } catch (IOException e) { throw new RuntimeException("File problem: " + e); } } for (Tree t : tb) { System.out.println("Original tree"); t.pennPrint(); System.out.println(); System.out.println("Tree transformed"); Tree tree = transformer.transformTree(t); tree.pennPrint(); System.out.println(); System.out.println("----------------------------"); } }
/** @return True if the CAS was successful, false if not */ @Override public Deferred<Boolean> call(final TreeRule fetched_rule) { TreeRule stored_rule = fetched_rule; final byte[] original_rule = stored_rule == null ? new byte[0] : JSON.serializeToBytes(stored_rule); if (stored_rule == null) { stored_rule = local_rule; } else { if (!stored_rule.copyChanges(local_rule, overwrite)) { LOG.debug(this + " does not have changes, skipping sync to storage"); throw new IllegalStateException("No changes detected in the rule"); } } // reset the local change map so we don't keep writing on subsequent // requests initializeChangedMap(); // validate before storing stored_rule.validateRule(); final PutRequest put = new PutRequest( tsdb.treeTable(), Tree.idToBytes(tree_id), Tree.TREE_FAMILY(), getQualifier(level, order), JSON.serializeToBytes(stored_rule)); return tsdb.getClient().compareAndSet(put, original_rule); }
// Each of these rules are from the read-tree manpage // go there to see what they mean. // Rule 0 is left out for obvious reasons :) public void testRules1thru3_NoIndexEntry() throws IOException { GitIndex index = new GitIndex(db); Tree head = new Tree(db); FileTreeEntry headFile = head.addFile("foo"); ObjectId objectId = ObjectId.fromString("ba78e065e2c261d4f7b8f42107588051e87e18e9"); headFile.setId(objectId); Tree merge = new Tree(db); Checkout readTree = getCheckoutImpl(head, index, merge); readTree.prescanTwoTrees(); assertTrue(readTree.removed().contains("foo")); readTree = getCheckoutImpl(merge, index, head); readTree.prescanTwoTrees(); assertEquals(objectId, readTree.updated().get("foo")); ObjectId anotherId = ObjectId.fromString("ba78e065e2c261d4f7b8f42107588051e87e18ee"); merge.addFile("foo").setId(anotherId); readTree = getCheckoutImpl(head, index, merge); readTree.prescanTwoTrees(); assertEquals(anotherId, readTree.updated().get("foo")); }
/** Test method for {@link com.fuerve.whiteboard.milestone2.structures.Tree#getParent()}. */ @Test public void testGetParent() { final Tree<Integer> target = new Tree<Integer>(); final Tree<Integer> targetParent = new Tree<Integer>(); targetParent.addChild(target); assertEquals(targetParent, target.getParent()); }
/** * Test method for {@link * com.fuerve.whiteboard.milestone2.structures.Tree#setDefaultTraversalMode(com.fuerve.whiteboard.milestone2.structures.Tree.TraversalMode)}. */ @Test public void testSetDefaultTraversalMode() { final Tree<Integer> target = new Tree<Integer>(); target.setDefaultTraversalMode(TraversalMode.INORDER); final Iterator<Integer> iter = target.iterator(); assertTrue(iter instanceof InOrderIterator<?>); }
public Forest(List<Tree> roots) { this.roots = roots; size = 0; for (Tree root : roots) { size += root.size(); } }
private Tree[] getTreeStack(String[] dirnames) throws Exception { Tree[] treeStack = new Tree[dirnames.length]; Pointer p = getRootPointer(); Tree tree = null; if (p == null) { tree = new Tree(); } else { tree = getTree(p); } treeStack[0] = tree; for (int i = 1; i < dirnames.length; i++) { String dirname = dirnames[i]; TreeEntry te = tree.getEntry(dirname); if (te == null || te.isFile()) { tree = new Tree(); } else { p = te.getPointer(); tree = getTree(p); } treeStack[i] = tree; } return treeStack; }
public POVConeLeafWriter(AbstractExporter exporter /*, Params params*/, Tree tree) { super(); this.exporter = exporter; this.w = exporter.getWriter(); this.tree = tree; this.povrayDeclarationPrefix = tree.getSpecies() + "_" + tree.getSeed() + "_"; }
@Inject public TreeFrameManager( final WindowManager windowManager, @GlobalConfig final AggregateConfigProvider globalConfig, @GlobalConfig final ColourManager colourManager, final ActiveFrameManager activeFrameManager, final SwingWindowFactory windowFactory, @PluginDomain(SwingController.class) final String domain, final EventBus eventBus, final SwingEventBus swingEventBus, final IconManager iconManager) { this.windowFactory = windowFactory; this.windowManager = windowManager; this.nodes = new HashMap<>(); this.config = globalConfig; this.colourManager = colourManager; this.activeFrameManager = activeFrameManager; this.eventBus = eventBus; this.swingEventBus = swingEventBus; this.iconManager = iconManager; UIUtilities.invokeLater( () -> { model = new TreeViewModel(config, new TreeViewNode(null, null)); tree = new Tree(this, model, swingEventBus, globalConfig, domain); tree.setCellRenderer(new TreeViewTreeCellRenderer(config, colourManager, this)); tree.setVisible(true); config.addChangeListener("treeview", this); config.addChangeListener("ui", "sortrootwindows", this); config.addChangeListener("ui", "sortchildwindows", this); config.addChangeListener("ui", "backgroundcolour", this); config.addChangeListener("ui", "foregroundcolour", this); }); }
public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Tree tree = new Tree(); int n = Integer.parseInt(br.readLine()); int nn = n - 1; TreeNode[] treeNodes = new TreeNode[n]; int i = 0; while (n-- > 0) { String[] strs = br.readLine().split(" "); int r = Integer.parseInt(strs[1]); int n1 = Integer.parseInt(strs[0]); treeNodes[i] = new TreeNode(n1, r); i = i + 1; } boolean[] x = new boolean[nn + 1]; while (nn-- > 0) { String[] strs = br.readLine().split(" "); int s = Integer.parseInt(strs[0]); int t = Integer.parseInt(strs[1]); if (!x[s]) { tree.insert(treeNodes[s]); x[s] = true; } if (!x[t]) { tree.insert(treeNodes[t]); x[t] = true; } } tree.levelOrder(tree.root); }
int getPreferredWidth() { int result = 0; Font font = parent.getHeaderFont(); if (text.length() > 0) { if (text.indexOf('\n') != -1) { result = TextSizeUtil.textExtent(font, text, 0).x; } else { result = TextSizeUtil.stringExtent(font, text).x; } } if (image != null) { result += image.getBounds().width; if (text.length() > 0) { result += MARGIN_IMAGE; } } if (sort != SWT.NONE) { result += SORT_INDICATOR_WIDTH; if (text.length() > 0 || image != null) { result += MARGIN_IMAGE; } } BoxDimensions headerPadding = parent.getThemeAdapter().getHeaderPadding(parent); // Add 1px for the right column border return result + headerPadding.left + headerPadding.right + 1; }
/*.................................................................................................................*/ public String getStringForTree(int ic) { if (treesBlock == null) return ""; Tree tree = treesBlock.getTree(ic); if (tree == null) return ""; if (tree.hasPolytomies(tree.getRoot())) return "Yes"; else return "No"; }
private void buildLessonTree(Response response) { TreeItem item = null; JsArray<LessonCategoryJS> lessonJSArray = JsonUtils.safeEval(response.getText()); for (int i = 0; i < lessonJSArray.length(); i++) { LessonCategoryJS lessonCategoryJS = lessonJSArray.get(i); TreeItem category = new TreeItem(); category.setText(lessonCategoryJS.getName()); JsArray<LessonJS> lessons = lessonCategoryJS.getChildren(); for (int j = 0; j < lessons.length(); j++) { LessonJS lesson = lessons.get(j); TreeItem lessonItem = new TreeItem(); Storage sessionStorage = Storage.getSessionStorageIfSupported(); String lastUrl = sessionStorage.getItem("lastUrl"); lessonItem.setText(lesson.getText()); category.addItem(lessonItem); lessonsTreeMap.put(lessonItem.getText(), lesson); if (lesson.getTechnology().equals(LessonTechnology.GWT.toString())) { addLessonToMap(lesson); } if (lastUrl != null && lastUrl.equals(lesson.getUrl())) { item = lessonItem; lessonPanel.setSelectedLesson(lesson); category.setState(true); } } lessonTree.addItem(category); } lessonTree.setSelectedItem(item); }
public Collection<Tree> read(final String fileName) throws IOException { List<Tree> result = new ArrayList<Tree>(); InputStream file = getClass().getResourceAsStream(fileName); if (file == null) { throw new IllegalArgumentException("File " + fileName + " not found"); } try { // Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(file); // Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); // Get iterator to all the rows in current sheet Iterator<Row> rowIterator = sheet.iterator(); rowIterator.next(); // ignore column title while (rowIterator.hasNext()) { Row row = rowIterator.next(); TreeBuilder reader = new TreeBuilder(row); Tree tree = reader.buildTree(); result.add(tree); System.out.println(tree.toString()); } } finally { file.close(); } return result; }
public Set<? extends Component> getAvailableAtClient() { if (!isCropper()) return null; final Tree tree = getTree(); final Component parent = getParent(); final Execution exe = Executions.getCurrent(); final String attrnm = VISIBLE_ITEM + tree.getUuid(); Map<Treeitem, Boolean> map = cast((Map) exe.getAttribute(attrnm)); if (map == null) { // Test very simple case first since getVisibleItems costly if (parent instanceof Treeitem) { for (Treeitem ti = (Treeitem) parent; ; ) { if (!ti.isOpen()) return Collections.emptySet(); Component gp = ti.getParent().getParent(); if (!(gp instanceof Treeitem)) break; ti = (Treeitem) gp; } } map = tree.getVisibleItems(); Executions.getCurrent().setAttribute(attrnm, map); } return map.keySet(); // yes, we return all visible items, not just direct children // in other words, we consider the whole tree as a single scope // See also bug 2814504 }
public Tree transformTree(Tree tree) { Label lab = tree.label(); if (tree.isLeaf()) { Tree leaf = tf.newLeaf(lab); leaf.setScore(tree.score()); return leaf; } String s = lab.value(); s = treebankLanguagePack().basicCategory(s); s = treebankLanguagePack().stripGF(s); int numKids = tree.numChildren(); List<Tree> children = new ArrayList<Tree>(numKids); for (int cNum = 0; cNum < numKids; cNum++) { Tree child = tree.getChild(cNum); Tree newChild = transformTree(child); children.add(newChild); } CategoryWordTag newLabel = new CategoryWordTag(lab); newLabel.setCategory(s); if (lab instanceof HasTag) { String tag = ((HasTag) lab).tag(); tag = treebankLanguagePack().basicCategory(tag); tag = treebankLanguagePack().stripGF(tag); newLabel.setTag(tag); } Tree node = tf.newTreeNode(newLabel, children); node.setScore(tree.score()); return node; }
public Tree transformTree(Tree tree) { Label lab = tree.label(); if (tree.isLeaf()) { Tree leaf = tf.newLeaf(lab); leaf.setScore(tree.score()); return leaf; } String s = lab.value(); s = treebankLanguagePack().basicCategory(s); int numKids = tree.numChildren(); List<Tree> children = new ArrayList<Tree>(numKids); for (int cNum = 0; cNum < numKids; cNum++) { Tree child = tree.getChild(cNum); Tree newChild = transformTree(child); // cdm 2007: for just subcategory stripping, null shouldn't happen // if (newChild != null) { children.add(newChild); // } } // if (children.isEmpty()) { // return null; // } CategoryWordTag newLabel = new CategoryWordTag(lab); newLabel.setCategory(s); if (lab instanceof HasTag) { String tag = ((HasTag) lab).tag(); tag = treebankLanguagePack().basicCategory(tag); newLabel.setTag(tag); } Tree node = tf.newTreeNode(newLabel, children); node.setScore(tree.score()); return node; }
@Test void treeTest() { tree.ready(20); boolean selected = tree.select("Grocery List", "Energy foods", "Coffee"); assertThat(selected, is(true)); }
/*..........................................ContinuousHistory................*/ private void fillDistribution(Tree tree, int node, ContinuousAdjustable dist) { if (tree.nodeIsTerminal(node)) { int t = tree.taxonNumberOfNode(node); for (int i = 0; i < getNumItems(); i++) dist.setState(t, i, getState(node, i)); } else for (int d = tree.firstDaughterOfNode(node); tree.nodeExists(d); d = tree.nextSisterOfNode(d)) fillDistribution(tree, d, dist); }
public boolean hasNext() { if (_tree == null || !_tree.inPagingMold()) return _it.hasNext(); Integer renderedCount = (Integer) _tree.getAttribute(Attributes.RENDERED_ITEM_COUNT); if (renderedCount == null || renderedCount.intValue() < _tree.getPaginal().getPageSize()) return _it.hasNext(); return false; }
/* * Trim BST - Given min and max trim the tree so that all nodes has values between min and max */ public Tree trimTree(Tree node, int min, int max) { if (node == null) return null; node.left = trimTree(node.left, min, max); node.right = trimTree(node.right, min, max); if (node.value < min) return node.right; else if (node.value > max) return node.left; else return node; }