generates an appropriate node label for a segment (useful for dot
    visualization).
423668
def get_segment_label(segment, segment_type, segment_text, ns, tokenized):
    
    segment_prefix = segment_type[0] if segment_type else '_'
    if tokenized:
        segment_label = u'[{0}]:{1}:segment:{2}'.format(
            segment_prefix, ns, segment.attrib['id'])
    else:
        # if the graph is not tokenized, put (the beginning of) the
        # segment's text into its label
        segment_label = u'[{0}]:{1}: {2}...'.format(
            segment_prefix, segment.attrib['id'], segment_text[:20])
    return segment_label
1023333
def build_dot(self):
        
        from graphviz import Digraph

        # Build GraphViz Digraph
        dot = Digraph()
        dot.attr("graph", 
                 bgcolor=self.theme["background_color"],
                 color=self.theme["outline_color"],
                 fontsize=self.theme["font_size"],
                 fontcolor=self.theme["font_color"],
                 fontname=self.theme["font_name"],
                 margin=self.theme["margin"],
                 rankdir="LR",
                 pad=self.theme["padding"])
        dot.attr("node", shape="box", 
                 style="filled", margin="0,0",
                 fillcolor=self.theme["fill_color"],
                 color=self.theme["outline_color"],
                 fontsize=self.theme["font_size"],
                 fontcolor=self.theme["font_color"],
                 fontname=self.theme["font_name"])
        dot.attr("edge", style="solid", 
                 color=self.theme["outline_color"],
                 fontsize=self.theme["font_size"],
                 fontcolor=self.theme["font_color"],
                 fontname=self.theme["font_name"])

        for k, n in self.nodes.items():
            label = "<tr><td cellpadding='6'>{}</td></tr>".format(n.title)
            if n.caption:
                label += "<tr><td>{}</td></tr>".format(n.caption)
            if n.repeat > 1:
                label += "<tr><td align='right' cellpadding='2'>x{}</td></tr>".format(n.repeat)
            label = "<<table border='0' cellborder='0' cellpadding='0'>" + label + "</table>>"
            dot.node(str(k), label)
        for a, b, label in self.edges:
            if isinstance(label, (list, tuple)):
                label = "x".join([str(l or "?") for l in label])

            dot.edge(str(a), str(b), label)
        return dot
1018667
def relabel(self, i):
        '''
        
        '''
        min_distance = 2*len(self.get_node_list()) + 1
        for j in self.get_neighbors(i):
            if (self.get_node_attr(j, 'distance') < min_distance and
                (self.get_edge_attr(i, j, 'flow') <
                 self.get_edge_attr(i, j, 'capacity'))):
                min_distance = self.get_node_attr(j, 'distance')
        for j in self.get_in_neighbors(i):
            if (self.get_node_attr(j, 'distance') < min_distance and
                self.get_edge_attr(j, i, 'flow') > 0):
                min_distance = self.get_node_attr(j, 'distance')
        self.set_node_attr(i, 'distance', min_distance + 1)
568327
function label(d) {

    delete d.d3plus_label

    if (vars.g.edges.selectAll("line, path").size() < vars.edges.large && vars.edges.label && d[vars.edges.label]) {

      if ("spline" in d.d3plus) {

        var length = this.getTotalLength(),
            center = this.getPointAtLength(length/2),
            prev = this.getPointAtLength((length/2)-(length*.1)),
            next = this.getPointAtLength((length/2)+(length*.1)),
            radians = Math.atan2(next.y-prev.y,next.x-prev.x),
            angle = radians*(180/Math.PI),
            bounding = this.parentNode.getBBox(),
            width = length*.8,
            x = center.x,
            y = center.y

      }
      else {

        var bounds = this.getBBox(),
            source = d[vars.edges.source],
            target = d[vars.edges.target],
            start = {"x": source.d3plus.edges[target[vars.id.value]].x, "y": source.d3plus.edges[target[vars.id.value]].y},
            end = {"x": target.d3plus.edges[source[vars.id.value]].x, "y": target.d3plus.edges[source[vars.id.value]].y},
            xdiff = end.x-start.x,
            ydiff = end.y-start.y,
            center = {"x": end.x-(xdiff)/2, "y": end.y-(ydiff)/2},
            radians = Math.atan2(ydiff,xdiff),
            angle = radians*(180/Math.PI),
            length = Math.sqrt((xdiff*xdiff)+(ydiff*ydiff)),
            width = length,
            x = center.x,
            y = center.y

      }

      width += vars.labels.padding*2

      var m = 0
      if (vars.edges.arrows.value) {
        m = typeof vars.edges.arrows.value === "number"
          ? vars.edges.arrows.value : 8
        m = m/vars.zoom.behavior.scaleExtent()[1]
        width -= m*2
      }

      if (angle < -90 || angle > 90) {
        angle -= 180
      }

      if (width*vars.zoom.behavior.scaleExtent()[0] > 20) {

        d.d3plus_label = {
          "x": x,
          "y": y,
          "translate": {"x": x, "y": y},
          "w": width,
          "h": 15+vars.labels.padding*2,
          "angle": angle,
          "anchor": "middle",
          "valign": "center",
          "color": vars.edges.color,
          "resize": false,
          "names": [vars.format.value(d[vars.edges.label])],
          "background": 1
        }

      }

    }

  }
671552
def showSegmentation(
        segmentation,
        voxelsize_mm=np.ones([3, 1]),
        degrad=4,
        label=1,
        smoothing=True
        ):
    
    labels = []

    segmentation = segmentation[::degrad, ::degrad, ::degrad]

    # import pdb; pdb.set_trace()
    mesh_data = seg2fem.gen_mesh_from_voxels_mc(segmentation, voxelsize_mm*degrad)
    if smoothing:
        mesh_data.coors = seg2fem.smooth_mesh(mesh_data)
    else:
        mesh_data = seg2fem.gen_mesh_from_voxels_mc(segmentation, voxelsize_mm * 1.0e-2)
        # mesh_data.coors +=
    vtk_file = "mesh_geom.vtk"
    mesh_data.write(vtk_file)
    QApplication(sys.argv)
    view = viewer.QVTKViewer(vtk_file)
    view.exec_()

    return labels
1160936
def _select_labels(self, segmentation, labels=None):
        

        logger.debug("select_labels() started with labels={}".format(labels))
        if self.slab is not None and labels is not None:
            segmentation_out = select_labels(segmentation, labels, slab=self.slab)
        else:
            logger.warning("Nothing found for labels " + str(labels))
            un = np.unique(segmentation)
            if len(un) < 2:
                logger.error("Just one label found in input segmenation")
            segmentation_out = (segmentation > un[0]).astype(segmentation.dtype)
        return segmentation_out
650896
def _generate_label_matrix(self):
        """"""
        self.L = np.zeros((self.n, self.m))
        self.Y = np.zeros(self.n, dtype=np.int64)
        for i in range(self.n):
            y = choice(self.k, p=self.p) + 1  # Note that y \in {1,...,k}
            self.Y[i] = y
            for j in range(self.m):
                p_j = self.parent.get(j, 0)
                prob_y = self.P_conditional(j, y, p_j, self.L[i, p_j], y)
                prob_0 = self.P_conditional(j, 0, p_j, self.L[i, p_j], y)
                p = np.ones(self.k + 1) * (1 - prob_y - prob_0) / (self.k - 1)
                p[0] = prob_0
                p[y] = prob_y
                self.L[i, j] = choice(self.k + 1, p=p)
1038134
def label(self, input_grid):
        
        unset = 0
        high_labels, num_labels = label(input_grid > self.high_thresh)
        region_ranking = np.argsort(maximum(input_grid, high_labels, index=np.arange(1, num_labels + 1)))[::-1]
        output_grid = np.zeros(input_grid.shape, dtype=int)
        stack = []
        for rank in region_ranking:
            label_num = rank + 1
            label_i, label_j = np.where(high_labels == label_num)
            for i in range(label_i.size):
                if output_grid[label_i[i], label_j[i]] == unset:
                    stack.append((label_i[i], label_j[i]))
            while len(stack) > 0:
                index = stack.pop()
                output_grid[index] = label_num
                for i in range(index[0] - 1, index[0] + 2):
                    for j in range(index[1] - 1, index[1] + 2):
                        if 0 <= i < output_grid.shape[0] and 0 <= j < output_grid.shape[1]:
                            if (input_grid[i, j] > self.low_thresh) and (output_grid[i, j] == unset):
                                stack.append((i, j))
        return output_grid
703966
def load_label(self, idx):
        
        label = scipy.io.loadmat('{}/segmentation/img_{}.mat'.format(self.nyud_dir, idx))['segmentation'].astype(np.uint8)
        label -= 1  # rotate labels
        label = label[np.newaxis, ...]
        return label
1242868
def generate_layout(bpmn_graph):
    
    classification = generate_elements_clasification(bpmn_graph)
    (sorted_nodes_with_classification, backward_flows) = topological_sort(bpmn_graph, classification[0])
    grid = grid_layout(bpmn_graph, sorted_nodes_with_classification)
    set_coordinates_for_nodes(bpmn_graph, grid)
    set_flows_waypoints(bpmn_graph)
1001983
def __add_segment(self, segment):
        
        segment_id = self.ns+':'+segment.attrib['id']
        self.segments.append(segment_id)
        segment_type, parent_segment_type = self.__get_segment_types(segment)
        segment_text = sanitize_string(segment.text)
        segment_label = get_segment_label(
            segment, segment_type, segment_text, self.ns, self.tokenized)

        self.add_node(
            segment_id, layers={self.ns, self.ns+':segment'},
            attr_dict={'label': segment_label,
                       self.ns+':text' : segment_text,
                       self.ns+':segment_type': segment_type})

        # store RST segment in list of EDUs
        self.edus.append(segment_id)

        if 'parent' in segment.attrib:
            self.__add_parent_relation(segment, segment_id, segment_type,
                                       parent_segment_type)
1096130
def cfg_to_dot(self, filename):
        
        with open(filename, 'w', encoding='utf8') as f:
            f.write('digraph{\n')
            for node in self.nodes:
                f.write('{}[label="{}"];\n'.format(node.node_id, str(node)))
                for son in node.sons:
                    f.write('{}->{};\n'.format(node.node_id, son.node_id))

            f.write("}\n")
617630
def to_dot(self, name='BDD'): # pragma: no cover
        
        parts = ['graph', name, '{']
        for node in self.dfs_postorder():
            if node is BDDNODEZERO:
                parts += ['n' + str(id(node)), '[label=0,shape=box];']
            elif node is BDDNODEONE:
                parts += ['n' + str(id(node)), '[label=1,shape=box];']
            else:
                v = _VARS[node.root]
                parts.append('n' + str(id(node)))
                parts.append('[label="{}",shape=circle];'.format(v))
        for node in self.dfs_postorder():
            if node is not BDDNODEZERO and node is not BDDNODEONE:
                parts += ['n' + str(id(node)), '--',
                          'n' + str(id(node.lo)),
                          '[label=0,style=dashed];']
                parts += ['n' + str(id(node)), '--',
                          'n' + str(id(node.hi)),
                          '[label=1];']
        parts.append('}')
        return " ".join(parts)
874287
def assign_node_labels_and_sizes(self):
        ""

        # shorthand
        nvals = self.ttree.get_node_values()

        # False == Hide nodes and labels unless user entered size 
        if self.style.node_labels is False:
            self.node_labels = ["" for i in nvals]           
            if self.style.node_sizes is not None:
                if isinstance(self.style.node_sizes, (list, tuple, np.ndarray)):
                    assert len(self.node_sizes) == len(self.style.node_sizes)
                    self.node_sizes = self.style.node_sizes

                elif isinstance(self.style.node_sizes, (int, str)):
                    self.node_sizes = (
                        [int(self.style.node_sizes)] * len(nvals)
                    )
                self.node_labels = [" " if i else "" for i in self.node_sizes]
                    
                    
        # True == Show nodes, label=idx, and show hover
        elif self.style.node_labels is True:
            # turn on node hover even if user did not set it explicit
            self.style.node_hover = True

            # get idx labels
            self.node_labels = self.ttree.get_node_values('idx', 1, 1)

            # use default node size as a list if not provided
            if not self.style.node_sizes:
                self.node_sizes = [18] * len(nvals)
            else:
                assert isinstance(self.style.node_sizes, (int, str))
                self.node_sizes = (
                    [int(self.style.node_sizes)] * len(nvals)
                )

        # User entered lists or other for node labels or sizes; check lengths.
        else:
            # make node labels into a list of values 
            if isinstance(self.style.node_labels, list):
                assert len(self.style.node_labels) == len(nvals)
                self.node_labels = self.style.node_labels

            # check if user entered a feature else use entered val
            elif isinstance(self.style.node_labels, str):
                self.node_labels = [self.style.node_labels] * len(nvals)
                if self.style.node_labels in self.ttree.features:
                    self.node_labels = self.ttree.get_node_values(
                        self.style.node_labels, 1, 0)

            # default to idx at internals if nothing else
            else:
                self.node_labels = self.ttree.get_node_values("idx", 1, 0)

            # make node sizes as a list; set to zero if node label is ""
            if isinstance(self.style.node_sizes, list):
                assert len(self.style.node_sizes) == len(nvals)
                self.node_sizes = self.style.node_sizes
            elif isinstance(self.style.node_sizes, (str, int, float)):
                self.node_sizes = [int(self.style.node_sizes)] * len(nvals)
            else:
                self.node_sizes = [18] * len(nvals)

            # override node sizes to hide based on node labels
            for nidx, node in enumerate(self.node_labels):
                if self.node_labels[nidx] == "":
                    self.node_sizes[nidx] = 0

        # ensure string type
        self.node_labels = [str(i) for i in self.node_labels]
621542
function NodeLabelView() {
        NodeParasiticView.apply(this, arguments);

        /** @member {string} */
        this.underline = false;

        this.enabled = true;
        this.movable = MM_FREE;
        this.sizable = SZ_NONE;
        this.text = "";
        this.horizontalAlignment = Graphics.AL_CENTER;
        this.verticalAlignment = Graphics.AL_MIDDLE;
    }
196860
static void appendDot(Node n, ControlFlowGraph<Node> inCFG,
      Appendable builder) throws IOException {
    new DotFormatter(n, inCFG, builder, false);
  }
1199964
def to_dot(self, name='EXPR'): # pragma: no cover
        """"""
        parts = ['graph', name, '{', 'rankdir=BT;']
        for ex in self.iter_dfs():
            exid = ex.node.id()
            if ex is Zero:
                parts += ["n{} [label=0,shape=box];".format(exid)]
            elif ex is One:
                parts += ["n{} [label=1,shape=box];".format(exid)]
            elif isinstance(ex, Literal):
                parts += ['n{} [label="{}",shape=box];'.format(exid, ex)]
            else:
                parts += ["n{0} [label={1.ASTOP},shape=circle];".format(exid, ex)]
        for ex in self.iter_dfs():
            exid = ex.node.id()
            if isinstance(ex, NotOp):
                parts += ["n{} -- n{};".format(ex.x.node.id(), exid)]
            elif isinstance(ex, ImpliesOp):
                p, q = ex.xs
                parts += ["n{} -- n{} [label=p];".format(p.node.id(), exid)]
                parts += ["n{} -- n{} [label=q];".format(q.node.id(), exid)]
            elif isinstance(ex, IfThenElseOp):
                s, d1, d0 = ex.xs
                parts += ["n{} -- n{} [label=s];".format(s.node.id(), exid)]
                parts += ["n{} -- n{} [label=d1];".format(d1.node.id(), exid)]
                parts += ["n{} -- n{} [label=d0];".format(d0.node.id(), exid)]
            elif isinstance(ex, NaryOp):
                for x in ex.xs:
                    parts += ["n{} -- n{};".format(x.node.id(), exid)]
        parts.append('}')
        return " ".join(parts)