annotate a tree in an external array using the given function
342975
def annotateTree(bT, fn):
    
    l = [None]*bT.traversalID.midEnd
    def fn2(bT):
        l[bT.traversalID.mid] = fn(bT)
        if bT.internal:
            fn2(bT.left)
            fn2(bT.right)
    fn2(bT)
    return l
340211
function() {
			// TODO: should I move this part to renderer? If so, how?
			var tree = this;
			var annotations = tree._treeModel.getAnnotations();
			// Remove existing annotations
			var existingAnnotations = this._parent.getElementsByClassName('treeAnnotationOn');
			var annotationsToRemove = [];
			for (var i = 0; i < existingAnnotations.length; i++){
				annotationsToRemove.push(existingAnnotations[i]);
			};
			annotationsToRemove.forEach(function(annotation) {
				while (annotation.firstChild) {
					annotation.removeChild(annotation.firstChild);
				}
				annotation.classList.remove('treeAnnotationOn');
			})
			// Add new annotations
			// A map from tree item ID to a list of its annotation HTML elements
			var annotationElementsByItem = {};
			var promises = [];
			annotations.forEach(function(annotation) {
				var promise = new Deferred();
				promises.push(promise);
				annotation.findDeepestFitId(tree._treeModel, function(id) {
					// Make sure there is a place to show the annotation
					if (!id) {
						promise.resolve();
						return;
					}
					var container = document.getElementById(id + 'Annotation');
					if (!container) {
						promise.resolve();
						return;
					}
					var annotationElement = annotation.generateHTML();
					if (!annotationElement) {
						promise.resolve();
						return;
					}
					if (!annotationElementsByItem[id]) {
						annotationElementsByItem[id] = [];
					}
					annotationElement.annotation = annotation;
					annotationElementsByItem[id].push(annotationElement);
					promise.resolve();
				});
			});
			Deferred.all(promises).then(function() {
				// All async calls ends. Add these annotations now.
				for (var elementid in annotationElementsByItem) {
					if (annotationElementsByItem.hasOwnProperty(elementid)) {
						var annotationsToAdd = annotationElementsByItem[elementid];
						var container = document.getElementById(elementid + 'Annotation');
						container.classList.add('treeAnnotationOn');
						// var html = annotationsToAdd[0];
						// container.appendChild(html);
						// if (annotationsToAdd.length > 1) {
						// 	var overlay = document.createElement('div');
						// 	overlay.classList.add('overlay');
						// 	container.appendChild(overlay);
						// }
						var showEditing = false;
						annotationsToAdd.forEach(function (html) {
						    container.appendChild(html);
							// Tooltip
							// TODO: make it general
							html.addEventListener('click', function(e) {
								if (tree.tooltip) {
									//tree.tooltip.remove();
								}
								var tooltip = document.createElement('div');
								tooltip.innerHTML = html.annotation.getDescription();
								tooltip.classList.add("treetable-tooltip");
								tooltip.style.left = e.clientX + 'px';
								tooltip.style.top = e.clientY + 'px';
								var cross = document.createElement('div');
								cross.innerHTML = '×';
								cross.classList.add("cross");
								tooltip.appendChild(cross);
								document.body.appendChild(tooltip);
								tooltip.remove = function (e2) {
									window.removeEventListener('click', tooltip.remove);
									document.body.removeChild(tooltip);
									tree.tooltip = null;
								};
								setTimeout(function() {
									window.addEventListener('click', tooltip.remove);
								}, 0);
								tree.tooltip = tooltip;
							});
						});
					}
				}
			});
		}
4539
protected void writeFunction( FunctionInputDef function)
    {
    xmlWriter_
      .element( FUNCTION_TAG)
      .attribute( NAME_ATR, function.getName())
      .content( () ->
        {
        writeAnnotations( function);
        for( String varType : function.getVarTypes())
          {
          writeInputs(
            varType,
            toStream( function.getVarDefs())
            .filter( varDef -> varDef.getType().equals( varType))
            .sorted());
          }
        })
      .write();
    }
1353927
function treeDFS(tree, callback) {
  for (let it of tree.slice()) {
    callback(it, tree);
    if (typeof it === 'object') {
      treeDFS(it.children, callback);
    }
  }
}
171503
function (tpl) {
      var tree = []
      var openTag
      var tag
      var name
      var paramStr
      var node
      var closeTag
      var usedExtends = 0

      for (openTag = this.findTag('', tpl); openTag; openTag = this.findTag('', tpl)) {
        if (openTag.index) {
          tree = tree.concat(this.parseText(tpl.slice(0, openTag.index)))
        }
        tpl = tpl.slice((openTag.index + openTag[0].length))
        tag = openTag[1].match(/^\s*(\w+)(.*)$/)
        if (tag) {
          // Function?!
          name = tag[1]
          paramStr = (tag.length > 2) ? tag[2].replace(/^\s+|\s+$/g, '') : ''
          if (name in this.buildInFunctions) {
            var buildIn = this.buildInFunctions[name]
            var params = ('parseParams' in buildIn ? buildIn.parseParams.bind(this) : this.parseParams.bind(this))(paramStr)
            if (buildIn.type === 'block') {
              // Remove new line after block open tag (like in Smarty)
              tpl = tpl.replace(/^\n/, '')
              closeTag = this.findCloseTag('/' + name, name + ' +[^}]*', tpl)
              var functionTree = buildIn.parse.call(this, params, tpl.slice(0, closeTag.index))
              if (functionTree) {
                // Some functions return false like {php} and {function}
                tree = tree.concat(functionTree)
              }
              tpl = tpl.slice(closeTag.index + closeTag[0].length)
            } else {
              if (name === 'extends') {
                // Anything before {extends} should be stripped.
                tree.splice(0, tree.length)
              }
              tree = tree.concat(buildIn.parse.call(this, params))
              if (name === 'extends') {
                usedExtends = tree.length
              }
            }
            tpl = tpl.replace(/^\n/, '')
          } else if (name in this.runTimePlugins) {
            // Possible it is function name. give it a priority before plugin.
            tree = tree.concat(this.parsePluginFunc(name, this.parseParams(paramStr)))
          } else if (name in this.plugins) {
            var plugin = this.plugins[name]
            if (plugin.type === 'block') {
              closeTag = this.findCloseTag('/' + name, name + ' +[^}]*', tpl)
              tree = tree.concat(this.parsePluginBlock(name, this.parseParams(paramStr), tpl.slice(0, closeTag.index)))
              tpl = tpl.slice(closeTag.index + closeTag[0].length)
            } else if (plugin.type === 'function') {
              tree = tree.concat(this.parsePluginFunc(name, this.parseParams(paramStr)))
            }
            if (name === 'append' || name === 'assign' || name === 'capture' || name === 'eval' || name === 'include') {
              tpl = tpl.replace(/^\n/, '')
            }
          } else {
            // Variable.
            node = this.buildInFunctions.expression.parse.call(this, openTag[1])
            tree.push(node)
          }
        } else {
          // Variable.
          node = this.buildInFunctions.expression.parse.call(this, openTag[1])
          if (node.expression.type === 'build-in' && node.expression.name === 'operator' && node.expression.op === '=') {
            tpl = tpl.replace(/^\n/, '')
          }
          tree.push(node)
        }
      }
      if (tpl) {
        tree = tree.concat(this.parseText(tpl))
      }
      tree.usedExtends = usedExtends
      return tree
    }
721188
def replace_function_node(node, annotation):
    
    target, funcs = parse_nni_function(annotation)
    FuncReplacer(funcs, target).visit(node)
    return node
237092
def parsed_function_to_ast(parsed: Parsed, parsed_key):
    """"""

    sub = parsed[parsed_key]

    subtree = {
        "type": "Function",
        "span": sub["span"],
        "function": {
            "name": sub["name"],
            "name_span": sub["name_span"],
            "parens_span": sub.get("parens_span", []),
        },
    }

    args = []
    for arg in parsed[parsed_key].get("args", []):

        # pdb.set_trace()

        if arg["type"] == "Function":
            args.append(parsed_function_to_ast(parsed, arg["span"]))
        elif arg["type"] == "NSArg":
            args.append(
                {
                    "arg": arg["arg"],
                    "type": arg["type"],
                    "span": arg["span"],
                    "nsarg": {
                        "ns": arg["ns"],
                        "ns_val": arg["ns_val"],
                        "ns_span": arg["ns_span"],
                        "ns_val_span": arg["ns_val_span"],
                    },
                }
            )
        elif arg["type"] == "StrArg":
            args.append({"arg": arg["arg"], "type": arg["type"], "span": arg["span"]})

    subtree["args"] = copy.deepcopy(args)

    return subtree
650676
function toArrayTree (array, options) {
  var opts = baseExports.assign({}, setupDefaults.treeOptions, options)
  var optStrict = opts.strict
  var optKey = opts.key
  var optParentKey = opts.parentKey
  var optChildren = opts.children
  var optSortKey = opts.sortKey
  var optReverse = opts.reverse
  var optData = opts.data
  var result = []
  var treeMap = {}
  var idList, id, treeData, parentId

  if (optSortKey) {
    array = arraySort(baseExports.clone(array), optSortKey)
    if (optReverse) {
      array = array.reverse()
    }
  }

  idList = arrayMap(array, function (item) {
    return item[optKey]
  })

  baseExports.each(array, function (item) {
    id = item[optKey]

    if (optData) {
      treeData = {}
      treeData[optData] = item
    } else {
      treeData = item
    }

    parentId = item[optParentKey]
    treeMap[id] = treeMap[id] || []
    treeMap[parentId] = treeMap[parentId] || []
    treeMap[parentId].push(treeData)
    treeData[optKey] = id
    treeData[optParentKey] = parentId
    treeData[optChildren] = treeMap[id]

    if (!optStrict || (optStrict && !parentId)) {
      if (!baseExports.includes(idList, parentId)) {
        result.push(treeData)
      }
    }
  })

  if (optStrict) {
    strictTree(array, optChildren)
  }

  return result
}
757048
function collectUniqNodes(list, func) {
    var result = [];
    var nodeIds = {};
    var currentNodeId;

    flexiEach(list, function(value) {
      flexiEach(func(value), function(node) {
        if (!nodeIds[currentNodeId = getNodeId(node)]) {
          result.push(node);
          nodeIds[currentNodeId] = true;
        }
      });
    });
    return result;
  }
280293
def annotate(row, ax, x='x', y='y', text='name', xytext=(7, -5), textcoords='offset points', **kwargs):
    
    # idx = row.name
    text = row[text] if text in row else str(text)
    x = row[x] if x in row else float(x)
    y = row[y] if y in row else float(y)
    ax.annotate(text, (row[x], row[y]), xytext=xytext, textcoords=textcoords, **kwargs)
    return row[text]
576744
function _each(array, func) {
        for (var i = 0, l = array.length; i < l; i++) {
            func(array[i]);
        }
    }
209325
function externalizeRow(row, columns, mapColumnIdToExtractFnName)
{
  var externalizedRow = {};
  for (var index = 0, length = columns.length; index < length; index++)
  {
    var column = columns[index];
    var extractFnName = mapColumnIdToExtractFnName[column.getId()];
    externalizedRow[column.getName()] = row[extractFnName](column.getId());
  }

  return externalizedRow;
}
1359063
function () {
			var tree,
				series = this,
				i = 0,
				parentList = [],
				allIds = [],
				key,
				insertItem = function (key) {
					each(parentList[key], function (item) {
						parentList[""].push(item);
					});
				},
				getNodeTree = function (id, i, level, list, points, parent) {
					var children = [],
						sortedChildren = [],
						childrenTotal = 0,
						val,
						point = points[i],
						nodeTree,
						node,
						insertNode,
						name;
					insertNode = function () {
						var i = 0,
							inserted = false;
						if (sortedChildren.length !== 0) {
							each(sortedChildren, function (child) {
								if (node.val > child.val && !inserted) {
									sortedChildren.splice(i, 0, node);
									inserted = true;
								}
								i = i + 1;					
							});
						} 
						if (!inserted) {
							sortedChildren.push(node);
						}
					};

					// Actions
					if (point) {
						name = point.name || "";
					}
					if (list[id] !== undefined) {
						each(list[id], function (i) {
							node = getNodeTree(points[i].id, i, (level + 1), list, points, id);
							childrenTotal += node.val;
							insertNode();
							children.push(node);
						});
					}
					val = pick((points[i] && points[i].value), childrenTotal, 0);
					nodeTree = {
						id: id,
						i: i,
						children: sortedChildren,
						childrenTotal: childrenTotal,
						val: val,
						level: level,
						parent: parent,
						name: name
					};
					series.nodeMap[nodeTree.id] = nodeTree;
					return nodeTree;
				};
			// Actions
			// Map children to index
			each(this.points, function (point) {
				var parent = "";
				allIds.push(point.id);
				if (point.parent !== undefined) {
					parent = point.parent;
				}
				if (parentList[parent] === undefined) {
					parentList[parent] = [];
				}
				parentList[parent].push(i);
				i = i + 1;
			});
			/* 
			*  Quality check:
			*  - If parent does not exist, then set parent to tree root
			*  - Add node id to parents children list
			*/  
			for (key in parentList) {
				if (parentList.hasOwnProperty(key)) {
					if (key !== "") {
						if (HighchartsAdapter.inArray(key, allIds) === -1) {
							insertItem(key);
							delete parentList[key];
						}
					}
				}
			}
			tree = getNodeTree("", -1, 0, parentList, this.points, null);
			return tree;
		}
1130533
def iter_tree_with_handed_function(self, function, *function_args):
        """"""
        def iter_all_children(row_iter, function, function_args):
            if isinstance(row_iter, Gtk.TreeIter):
                function(row_iter, *function_args)
                for n in reversed(range(self.tree_store.iter_n_children(row_iter))):
                    child_iter = self.tree_store.iter_nth_child(row_iter, n)
                    iter_all_children(child_iter, function, function_args)
            else:
                self._logger.warning("Iter has to be TreeIter -> handed argument is: {0}".format(row_iter))

        # iter on root level of tree
        next_iter = self.tree_store.get_iter_first()
        while next_iter:
            iter_all_children(next_iter, function, function_args)
            next_iter = self.tree_store.iter_next(next_iter)
154190
function Tree(details) {

		// If the details are not an Object
		if(!is.object(details)) {
			throw 'details must be an Object';
		}

		// If the name is not set
		if(!('__name__' in details)) {
			throw '"__name__" not found in details';
		}

		// If the name is not valid
		if(!_standardField.test(details['__name__'])) {
			throw '"__name__" not a valid value for Tree';
		}

		// Store the name then delete it
		var _name = details['__name__'];
		delete details['__name__'];

		// If for some reason the array flag is set, remove it
		if('__array__' in details) {
			delete details['__array__'];
		}

		// Call the parent constructor
		Parent.call(this, details);

		/**
		 * To Object
		 *
		 * Returns the Node as a dictionary in the same format as is used in
		 * constructing it
		 *
		 * @name toObject
		 * @return Object
		 */
		this.toObject = function toObject() {

			// Init the Object we will return
			var oRet = {
				"__name__": _name
			}

			// Get the parents dict and add it to the return
			var oParent = Parent.prototype.toObject.call(this);
			for(var k in oParent) {
				oRet[k] = oParent[k];
			}

			// Return
			return oRet;
		}

		/**
		 * Type
		 *
		 * Returns the type of Node
		 *
		 * @name type
		 * @access public
		 * @return String
		 */
		this.type = function type() {
			return 'Tree';
		}

		/**
		 * Valid
		 *
		 * Checks if the passed dict has the right values for this Parent
		 *
		 * @name valid
		 * @param Object value				The value to validate
		 * @return bool
		 */
		this.valid = function valid(value, include_name) {

			// If the include_name param wasn't sent, assume true
			if(typeof include_name == 'undefined') {
				include_name = true;
			}

			// Call the Parent valid method
			return Parent.prototype.valid.call(this, value, (include_name ? [_name] : []));
		}
	}
370976
function toTreeArray (array, options) {
  return unTreeList([], array, baseExports.assign({}, setupDefaults.treeOptions, options))
}
444774
def _annotate(ax, annotate, height, left, width):
    
    annotate_yrange_factor = 0.010
    xticks = np.array(left) + width / 2.0
    ymin, ymax = ax.get_ylim()
    yrange = ymax - ymin

    # Reset ymax and ymin so there's enough room to see the annotation of
    # the top-most
    if ymax > 0:
        ymax += yrange * 0.15
    if ymin < 0:
        ymin -= yrange * 0.15
    ax.set_ylim(ymin, ymax)
    yrange = ymax - ymin

    offset_ = yrange * annotate_yrange_factor
    if isinstance(annotate, collections.Iterable):
        annotations = map(str, annotate)
    else:
        annotations = ['%.3f' % h if type(h) is np.float_ else str(h)
                       for h in height]
    for x, h, annotation in zip(xticks, height, annotations):
        # Adjust the offset to account for negative bars
        offset = offset_ if h >= 0 else -1 * offset_
        verticalalignment = 'bottom' if h >= 0 else 'top'

        if len(str(annotation)) > 6:
            size = 7
        elif len(str(annotation)) > 5:
            size = 8
        else:
            size = 10
        # Finally, add the text to the axes
        ax.annotate(annotation, (x, h + offset),
                    verticalalignment=verticalalignment,
                    horizontalalignment='center',
                    size=size)