Format graph as Makefile.
549166
def makefile(graph):
    """"""
    from renku.models.provenance.activities import ProcessRun, WorkflowRun

    for activity in graph.activities.values():
        if not isinstance(activity, ProcessRun):
            continue
        elif isinstance(activity, WorkflowRun):
            steps = activity.subprocesses.values()
        else:
            steps = [activity]

        for step in steps:
            click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs))
            tool = step.process
            click.echo(
                '\t@' + ' '.join(tool.to_argv()) + ' ' + ' '.join(
                    tool.STD_STREAMS_REPR[key] + ' ' + str(path)
                    for key, path in tool._std_streams().items()
                )
            )
1183561
def save(self, cf, filename, format='dot'):
        
        try:
            dot_graph = Dot(**self.graph_format)

            # add nodes
            nodes = {}
            for cfg_addr in cf._graph.node.keys():
                nodes[cfg_addr] = self._create_node(cfg_addr, cf)

                dot_graph.add_node(nodes[cfg_addr])

            # add edges
            for cfg_src_addr in cf._graph.node.keys():
                for cfg_dst_addr in cf._edges.get(cfg_src_addr, []):
                    edge = self._create_edge(nodes, cfg_src_addr, cfg_dst_addr)

                    dot_graph.add_edge(edge)

            dot_graph.write("{}.{}".format(filename, format), format=format)
        except Exception:
            logger.error("Failed to save call graph: %s (%s)", filename, format, exc_info=True)
721693
def format_output(groups, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}'
    for g in groups['AutoScalingGroups']:
        out.append(line_format.format(
            g['AutoScalingGroupName'],
            g['LaunchConfigurationName'],
            'desired:'+str(g['DesiredCapacity']),
            'max:'+str(g['MaxSize']),
            'min:'+str(g['MinSize']),
            g['CreatedTime'].strftime('%Y/%m/%d %H:%M:%S'),
        ))
    return out
409353
def format_graphviz_lines(lines):
    
    # first, prepare the unique list of all nodes (sources and targets)
    lines_nodes = set()

    for line in lines:
        lines_nodes.add(line['source'])
        lines_nodes.add(line['target'])

    # generate a list of all nodes and their names for graphviz graph
    nodes = OrderedDict()

    for i, node in enumerate(sorted(lines_nodes)):
        nodes[node] = 'n{}'.format(i+1)

    # print(lines_nodes, nodes)

    graph = list()

    # some basic style definition
    # https://graphviz.gitlab.io/_pages/doc/info/lang.html
    graph.append('digraph G {')

    # https://graphviz.gitlab.io/_pages/doc/info/shapes.html#record
    graph.append('\tgraph [ center=true, margin=0.75, nodesep=0.5, ranksep=0.75, rankdir=LR ];')
    graph.append('\tnode [ shape=box, style="rounded,filled" width=0, height=0, '
                 'fontname=Helvetica, fontsize=11 ];')
    graph.append('\tedge [ fontname=Helvetica, fontsize=9 ];')

    # emit nodes definition
    graph.append('\n\t// nodes')

    # https://www.graphviz.org/doc/info/colors.html#brewer
    group_colors = dict()

    for label, name in nodes.items():
        if ':' in label:
            (group, label) = str(label).split(':', 1)

            # register a new group for coloring
            if group not in group_colors:
                group_colors[group] = len(group_colors.keys()) + 1
        else:
            group = None

        label = escape_graphviz_entry(label)

        graph.append('\t{name} [label="{label}"{group}];'.format(
            name=name,
            label="{}\\n{}".format(group, label) if group is not None else label,
            group=' group="{}" colorscheme=pastel28 color={}'.format(
                group, group_colors[group]) if group is not None else ''
        ))

    # now, connect the nodes
    graph.append('\n\t// edges')
    for line in lines:
        label = line.get('metadata', '')

        graph.append('\t{source} -> {target} [{label}];'.format(
            source=nodes[line['source']],
            target=nodes[line['target']],
            label='label="{}"'.format(escape_graphviz_entry(label)) if label != '' else ''
        ))

    graph.append('}')

    return '\n'.join(graph)
224772
def formatFunctionNode(node,path,stack):
    ''''''
    #node.name is already defined by AST module
    node.weight = calcFnWeight(node)
    node.path   = path
    node.pclass = getCurrentClass(stack)
    return node
1238212
def dom_lt(graph):
    """"""

    def _dfs(v, n):
        semi[v] = n = n + 1
        vertex[n] = label[v] = v
        ancestor[v] = 0
        for w in graph.all_sucs(v):
            if not semi[w]:
                parent[w] = v
                n = _dfs(w, n)
            pred[w].add(v)
        return n

    def _compress(v):
        u = ancestor[v]
        if ancestor[u]:
            _compress(u)
            if semi[label[u]] < semi[label[v]]:
                label[v] = label[u]
            ancestor[v] = ancestor[u]

    def _eval(v):
        if ancestor[v]:
            _compress(v)
            return label[v]
        return v

    def _link(v, w):
        ancestor[w] = v

    parent, ancestor, vertex = {}, {}, {}
    label, dom = {}, {}
    pred, bucket = defaultdict(set), defaultdict(set)

    # Step 1:
    semi = {v: 0 for v in graph.nodes}
    n = _dfs(graph.entry, 0)
    for i in range(n, 1, -1):
        w = vertex[i]
        # Step 2:
        for v in pred[w]:
            u = _eval(v)
            y = semi[w] = min(semi[w], semi[u])
        bucket[vertex[y]].add(w)
        pw = parent[w]
        _link(pw, w)
        # Step 3:
        bpw = bucket[pw]
        while bpw:
            v = bpw.pop()
            u = _eval(v)
            dom[v] = u if semi[u] < semi[v] else pw
    # Step 4:
    for i in range(2, n + 1):
        w = vertex[i]
        dw = dom[w]
        if dw != vertex[semi[w]]:
            dom[w] = dom[dw]
    dom[graph.entry] = None
    return dom
1219278
def show_graph(self, format='svg'):
        
        g = self.to_simple_graph(AssetExists())
        if format == 'svg':
            return g.svg
        elif format == 'png':
            return g.png
        elif format == 'jpeg':
            return g.jpeg
        else:
            # We should never get here because of the expect_element decorator
            # above.
            raise AssertionError("Unknown graph format %r." % format)
136665
def makefile(self):
        
        return self.env.get_template('Makefile.j2').render(
            metadata=self.metadata,
            package=self.package)
809787
def cli(input, verbose, quiet, output_format, precision, indent):
    """"""

    verbosity = verbose - quiet
    configure_logging(verbosity)
    logger = logging.getLogger('geomet')

    # Handle the case of file, stream, or string input.
    try:
        src = click.open_file(input).readlines()
    except IOError:
        src = [input]

    stdout = click.get_text_stream('stdout')

    # Read-write loop.
    try:
        for line in src:
            text = line.strip()
            logger.debug("Input: %r", text)
            output = translate(
                text,
                output_format=output_format,
                indent=indent,
                precision=precision
            )
            logger.debug("Output: %r", output)
            stdout.write(output)
            stdout.write('\n')
        sys.exit(0)
    except Exception:
        logger.exception("Failed. Exception caught")
        sys.exit(1)
1054900
def plot_diagrams(results, configs, compiler, out_dir):
    """"""
    compiler_fn = make_filename(compiler)
    total = psutil.virtual_memory().total  # pylint:disable=I0011,E1101
    memory = int(math.ceil(byte_to_gb(total)))

    images_dir = os.path.join(out_dir, 'images')

    for config in configs:
        out_prefix = '{0}_{1}'.format(config['name'], compiler_fn)

        plot_diagram(
            config,
            results,
            images_dir,
            os.path.join(images_dir, '{0}.png'.format(out_prefix))
        )

        with open(
            os.path.join(out_dir, '{0}.qbk'.format(out_prefix)),
            'wb'
        ) as out_f:
            qbk_content = """{0}
Measured on a {2} host with {3} GB memory. Compiler used: {4}.

[$images/metaparse/{1}.png [width 100%]]
""".format(config['desc'], out_prefix, platform.platform(), memory, compiler)
            out_f.write(qbk_content)
881097
def get_makefile_filename():
    """"""
    if _PYTHON_BUILD:
        return os.path.join(_PROJECT_BASE, "Makefile")
    if hasattr(sys, 'abiflags'):
        config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags)
    else:
        config_dir_name = 'config'
    return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
777433
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations,
            no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose):
    """"""
    if verbose:
        logging.basicConfig(level=logging.DEBUG)
        log.setLevel(logging.DEBUG)
        log.debug('using connection: %s', manager.engine.url)

    click.secho('Compilation', fg='red', bold=True)
    if skip_tqdm:
        click.echo('```')
    graph = from_path(
        path,
        manager=manager,
        use_tqdm=(not (skip_tqdm or verbose)),
        allow_nested=allow_nested,
        allow_naked_names=allow_naked_names,
        disallow_unqualified_translocations=disallow_unqualified_translocations,
        citation_clearing=(not no_citation_clearing),
        required_annotations=required_annotations,
        no_identifier_validation=no_identifier_validation,
        allow_definition_failures=True,
    )
    if skip_tqdm:
        click.echo('```')
    to_pickle(graph, get_corresponding_pickle_path(path))

    click.echo('')
    _print_summary(graph, ticks=skip_tqdm)

    sys.exit(0 if 0 == graph.number_of_warnings() else 1)
172517
def dot_format(out, graph, name="digraph"):
    """"""

    out.write("digraph %s {\n" % name)
    for step, deps in each_step(graph):
        for dep in deps:
            out.write("  \"%s\" -> \"%s\";\n" % (step, dep))

    out.write("}\n")
717118
def _get_graph(graph, filename):
    """"""
    try:
        rendered = graph.rendered_file
    except AttributeError:
        try:
            graph.render(os.path.join(server.tmpdir, filename), format='png')
            rendered = filename
        except OSError:
            rendered = None
    graph.rendered_file = rendered
    return rendered
536049
def _gen_machine_graph(start, end, force_overwrite=False):
    
    filename = graphs.get_machine_graph_filename(start, end)
    csv_filename = os.path.join(GRAPH_ROOT, filename + '.csv')
    png_filename = os.path.join(GRAPH_ROOT, filename + '.png')

    _check_directory_exists(csv_filename)
    _check_directory_exists(png_filename)

    if not settings.GRAPH_DEBUG or force_overwrite:
        if os.path.exists(csv_filename):
            if os.path.exists(png_filename):
                return

    machine_list = Machine.objects.all()

    plt.subplots(figsize=(4, 4))

    data = []
    labels = []

    with open(csv_filename, 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        for machine in machine_list.iterator():
            hours, jobs = usage.get_machine_usage(machine, start, end)
            if hours > 0:
                csv_writer.writerow([machine.name, hours, jobs])
                data.append(hours)
                labels.append(machine.name)

    plt.pie(data, labels=labels, autopct='%1.1f%%', shadow=True)

    del data
    del labels

    plt.tight_layout()
    plt.savefig(png_filename)
    plt.close()
1239794
def cmd_tree(conf: Config):
    """"""
    build_context = BuildContext(conf)
    populate_targets_graph(build_context, conf)

    def print_target_with_deps(target, depth=2):
        print('{: >{}}{}'.format('+-', depth, target.name))
        for dep in sorted(
                build_context.target_graph.neighbors(target.name)):
            print_target_with_deps(build_context.targets[dep], depth + 2)

    if conf.targets:
        for target_name in sorted(parse_target_selectors(conf.targets, conf)):
            mod, name = split(target_name)
            if name == '*':
                for target_name in sorted(
                        build_context.targets_by_module[mod]):
                    print_target_with_deps(build_context.targets[target_name])
            else:
                print_target_with_deps(build_context.targets[target_name])
    else:
        for _, target in sorted(build_context.targets.items()):
            print_target_with_deps(target)
180062
def makediagram(edges):
    """"""
    graph = pydot.Dot(graph_type='digraph')
    nodes = edges2nodes(edges)
    epnodes = [(node, 
        makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
    endnodes = [(node, 
        makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"]
    epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)]
    nodedict = dict(epnodes + epbr + endnodes)
    for value in list(nodedict.values()):
        graph.add_node(value)
    for e1, e2 in edges:
        graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2]))
    return graph