Creates a rst.sty Latex string representation of a multi-satellite RST subtree
    (i.e. a set of nucleus-satellite relations that share the same nucleus.
168422
def make_multisat(nucsat_tuples):
    
    nucsat_tuples = [tup for tup in nucsat_tuples]  # unpack the iterable, so we can check its length
    assert len(nucsat_tuples) > 1, \
        "A multisat relation bundle must contain more than one relation"

    result = "\dirrel\n\t"
    first_relation, remaining_relations = nucsat_tuples[0], nucsat_tuples[1:]
    
    relname, nuc_types, elements = first_relation
    first_nucleus_pos = current_nucleus_pos = nuc_types.index('N')
    result_segments = []
    
    for i, nuc_type in enumerate(nuc_types):
        if nuc_type == 'N':
            result_segments.append(NUC_TEMPLATE.substitute(nucleus=elements[i]))
        else:
            result_segments.append(SAT_TEMPLATE.substitute(satellite=elements[i], relation=relname))
    
    for (relname, nuc_types, elements) in remaining_relations:
        for i, nuc_type in enumerate(nuc_types):
            if nuc_type == 'N':  # all relations share the same nucleus, so we don't need to reprocess it.
                continue
            else:
                result_segment = SAT_TEMPLATE.substitute(satellite=elements[i], relation=relname)
                if i < first_nucleus_pos:  # satellite comes before the nucleus
                    result_segments.insert(current_nucleus_pos, result_segment)
                    current_nucleus_pos += 1
                else:
                    result_segments.append(result_segment)
    
    return result + '\n\t'.join(result_segments)
899662
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
    
    return Text(string, token)
177599
def create_module_rst_file(module_name):
    

    return_text = 'Module:  ' + module_name
    dash = '=' * len(return_text)
    return_text += '\n' + dash + '\n\n'
    return_text += '.. automodule:: ' + module_name + '\n'
    return_text += '   :members:\n\n'

    return return_text
1064650
private IRenderingElement generatePolymerSgroup(Sgroup sgroup, Map<IAtom, AtomSymbol> symbolMap) {
        // draw the brackets
        List<SgroupBracket> brackets = sgroup.getValue(SgroupKey.CtabBracket);
        if (brackets != null) {

            SgroupType type = sgroup.getType();

            String subscript = sgroup.getValue(SgroupKey.CtabSubScript);
            String connectivity = sgroup.getValue(SgroupKey.CtabConnectivity);

            switch (type) {
                case CtabCopolymer:
                    subscript = "co";
                    String subtype = sgroup.getValue(SgroupKey.CtabSubType);
                    if ("RAN".equals(subtype))
                        subscript = "ran";
                    else if ("BLK".equals(subtype))
                        subscript = "blk";
                    else if ("ALT".equals(subtype))
                        subscript = "alt";
                    break;
                case CtabCrossLink:
                    subscript = "xl";
                    break;
                case CtabAnyPolymer:
                    subscript = "any";
                    break;
                case CtabGraft:
                    subscript = "grf";
                    break;
                case CtabMer:
                    subscript = "mer";
                    break;
                case CtabMonomer:
                    subscript = "mon";
                    break;
                case CtabModified:
                    subscript = "mod";
                    break;
                case CtabStructureRepeatUnit:
                    if (subscript == null)
                        subscript = "n";
                    if (connectivity == null)
                        connectivity = "eu";
                    break;
            }

            // connectivity doesn't matter if symmetric... which is hard to test
            // here but we can certainly ignore it for single atoms (e.g. methylene)
            // also when we see brackets we presume head-to-tail repeating
            if ("ht".equals(connectivity) || sgroup.getAtoms().size() == 1)
                connectivity = null;

            return generateSgroupBrackets(sgroup,
                                          brackets,
                                          symbolMap,
                                          subscript,
                                          connectivity);
        } else {
            return new ElementGroup();
        }
    }
1228431
def _construct(self, strings_collection):
        
        
        # 1. Add a unique character to each string in the collection
        strings_collection = utils.make_unique_endings(strings_collection)
    
        ############################################################
        # 2. Build the GST using modified Ukkonnen's algorithm     #
        ############################################################
        
        root = ast.AnnotatedSuffixTree.Node()
        root.strings_collection = strings_collection
        # To preserve simplicity
        root.suffix_link = root
        root._arc = (0,-1,0)
        # For constant updating of all leafs, see [Gusfield {RUS}, p. 139]
        root._e = [0 for _ in xrange(len(strings_collection))]
        
        
        def _ukkonen_first_phases(string_ind):
            """
            Looks for the part of the string which is already encoded.
            Returns a tuple of form
            ([length of already encoded string preffix],
             [tree node to start the first explicit phase with],
             [path to go down at the beginning of the first explicit phase]).
            
            """
            already_in_tree = 0
            suffix = strings_collection[string_ind]
            starting_path = (0, 0, 0)
            starting_node = root
            child_node = starting_node.chose_arc(suffix)
            while child_node:
                (str_ind, substr_start, substr_end) = child_node.arc()
                match = utils.match_strings(
                            suffix, strings_collection[str_ind][substr_start:substr_end])
                already_in_tree += match
                if match == substr_end-substr_start:
                    # matched the arc, proceed with child node
                    suffix = suffix[match:]
                    starting_node = child_node
                    child_node = starting_node.chose_arc(suffix)
                else:
                    # otherwise we will have to proceed certain path at the beginning
                    # of the first explicit phase
                    starting_path = (str_ind, substr_start, substr_start+match)
                    break
            # For constant updating of all leafs, see [Gusfield {RUS}, p. 139]
            root._e[string_ind] = already_in_tree
                
            return (already_in_tree, starting_node, starting_path)
        
        def _ukkonen_phase(string_ind, phase, starting_node, starting_path, starting_continuation):
            """
            Ukkonen's algorithm single phase.
            Returns a tuple of form:
            ([tree node to start the next phase with],
             [path to go down at the beginning of the next phase],
             [starting continuation for the next phase]).
            
            """
            current_suffix_end = starting_node
            suffix_link_source_node = None
            path_str_ind, path_substr_start, path_substr_end = starting_path
            # Continuations [starting_continuation..(i+1)]
            for continuation in xrange(starting_continuation, phase+1):
                # Go up to the first node with suffix link [no more than 1 pass]
                if continuation > starting_continuation:
                    path_str_ind, path_substr_start, path_substr_end = 0, 0, 0
                    if not current_suffix_end.suffix_link:
                        (path_str_ind, path_substr_start, path_substr_end) = current_suffix_end.arc()
                        current_suffix_end = current_suffix_end.parent
                    if current_suffix_end.is_root():
                        path_str_ind = string_ind
                        path_substr_start = continuation
                        path_substr_end = phase
                    else:
                        # Go through the suffix link
                        current_suffix_end = current_suffix_end.suffix_link
                        
                # Go down the path (str_ind, substr_start, substr_end)
                # NB: using Skip/Count trick,
                # see [Gusfield {RUS} p.134] for details
                g = path_substr_end - path_substr_start
                if g > 0:
                    current_suffix_end = current_suffix_end.chose_arc(strings_collection
                                         [path_str_ind][path_substr_start])
                (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc()
                g_ = cs_ss_end - cs_ss_start
                while g >= g_:
                    path_substr_start += g_
                    g -= g_
                    if g > 0:
                        current_suffix_end = current_suffix_end.chose_arc(strings_collection
                                             [path_str_ind][path_substr_start])
                    (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc()
                    g_ = cs_ss_end - cs_ss_start
                    
                # Perform continuation by one of three rules,
                # see [Gusfield {RUS} p. 129] for details
                if g == 0:
                    # Rule 1
                    if current_suffix_end.is_leaf():
                        pass
                    # Rule 2a
                    elif not current_suffix_end.chose_arc(strings_collection[string_ind][phase]):
                        if suffix_link_source_node:
                            suffix_link_source_node.suffix_link = current_suffix_end
                        new_leaf = current_suffix_end.add_new_child(string_ind, phase, -1)
                        new_leaf.weight = 1
                        if continuation == starting_continuation:
                            starting_node = new_leaf
                            starting_path = (0, 0, 0)
                    # Rule 3a
                    else:
                        if suffix_link_source_node:
                            suffix_link_source_node.suffix_link = current_suffix_end
                        starting_continuation = continuation
                        starting_node = current_suffix_end
                        starting_path = (string_ind, phase, phase+1)
                        break
                    suffix_link_source_node = None
                else:
                    (si, ss, se) = current_suffix_end._arc
                    # Rule 2b
                    if strings_collection[si][ss + g] != strings_collection[string_ind][phase]:
                        parent = current_suffix_end.parent
                        parent.remove_child(current_suffix_end)
                        current_suffix_end._arc = (si, ss+g, se)
                        new_node = parent.add_new_child(si, ss, ss + g)
                        new_leaf = new_node.add_new_child(string_ind, phase, -1)
                        new_leaf.weight = 1
                        if continuation == starting_continuation:
                            starting_node = new_leaf
                            starting_path = (0, 0, 0)
                        new_node.add_child(current_suffix_end)
                        if suffix_link_source_node:
                            # Define new suffix link
                            suffix_link_source_node.suffix_link = new_node
                        suffix_link_source_node = new_node
                        current_suffix_end = new_node
                    # Rule 3b
                    else:
                        suffix_link_source_node = None
                        starting_continuation = continuation
                        starting_node = current_suffix_end.parent
                        starting_path = (si, ss, ss+g+1)
                        break
            
            # Constant updating of all leafs, see [Gusfield {RUS}, p. 139]
            starting_node._e[string_ind] += 1
            
            return starting_node, starting_path, starting_continuation
                        
        for m in xrange(len(strings_collection)):
            # Check for phases 1..x that are already in tree
            starting_phase, starting_node, starting_path = _ukkonen_first_phases(m)
            starting_continuation = 0
            # Perform phases (x+1)..n explicitly
            for phase in xrange(starting_phase, len(strings_collection[m])):
                starting_node, starting_path, starting_continuation = \
                    _ukkonen_phase(m, phase, starting_node, starting_path, starting_continuation)
                    
        
        ############################################################
        ############################################################
        ############################################################
        
        # 3. Delete degenerate first-level children
        for k in root.children.keys():
            (ss, si, se) = root.children[k].arc()
            if (se - si == 1 and
                ord(strings_collection[ss][si]) >= consts.String.UNICODE_SPECIAL_SYMBOLS_START):
                del root.children[k]
        
        # 4. Make a depth-first bottom-up traversal and annotate
        #    each node by the sum of its children;
        #    each leaf is already annotated with '1'.
        def _annotate(node):
            weight = 0
            for k in node.children:
                if node.children[k].weight > 0:
                    weight += node.children[k].weight
                else:
                    weight += _annotate(node.children[k])
            node.weight = weight
            return weight
        _annotate(root)
        
        return root
245146
def strand(s1, s2):
    
    return "".join(map(lambda x,y:chr(ord(x)&ord(y)), s1, s2))
1329047
def serialize_text_node(self, elt, sw, pyobj):
        '''
        '''
        textNode = None
        if pyobj is not None:
            text = self.get_formatted_content(pyobj)
            if type(text) not in _stringtypes:
                raise TypeError, 'pyobj must be a formatted string'

            textNode = elt.createAppendTextNode(text)

        return textNode
164154
def gen_body(self):
        
        # We need to sort the treepositions, as RSTTool relies on <segment>
        # elements to be in linear order of the EDUs in the text.
        for treepos in sorted(self.treepositions):
            node = self.dgtree[treepos]
            node_id = self.get_node_id(treepos)
            node_type = get_node_type(node)

            if node_type in (TreeNodeTypes.leaf_node,
                             TreeNodeTypes.relation_node):
                relname, parent_id = self.get_relname_and_parent(treepos)

                attrib_list = [('id', node_id)]
                if parent_id is not None:
                    attrib_list.extend([('parent', parent_id), ('relname', relname)])

                if node_type == TreeNodeTypes.leaf_node:
                    self.body['segments'].append(E('segment', node, OrderedDict(attrib_list)))

                else:  # node_type == TreeNodeTypes.relation_node:
                    group_type = self.get_group_type(treepos)
                    # insert 'type' attrib between 'id' and 'parent'
                    attrib_list.insert(1, ('type', group_type))
                    self.body['groups'].append(E('group', OrderedDict(attrib_list)))
572451
def make_strslice(lineno, s, lower, upper):
    
    return symbols.STRSLICE.make_node(lineno, s, lower, upper)
479419
def rsdl_r(self, AX, Y):
        

        # Avoid calling cnst_c() more than once in case it is expensive
        # (e.g. due to allocation of a large block of memory)
        if not hasattr(self, '_cnst_c'):
            self._cnst_c = self.cnst_c()
        return AX + self.cnst_B(Y) - self._cnst_c
1215042
def fixup_simple_stmt(parent, i, stmt_node):
    
    for semi_ind, node in enumerate(stmt_node.children):
        if node.type == token.SEMI: # *sigh*
            break
    else:
        return

    node.remove() # kill the semicolon
    new_expr = Node(syms.expr_stmt, [])
    new_stmt = Node(syms.simple_stmt, [new_expr])
    while stmt_node.children[semi_ind:]:
        move_node = stmt_node.children[semi_ind]
        new_expr.append_child(move_node.clone())
        move_node.remove()
    parent.insert_child(i, new_stmt)
    new_leaf1 = new_stmt.children[0].children[0]
    old_leaf1 = stmt_node.children[0].children[0]
    new_leaf1.prefix = old_leaf1.prefix
1244600
def copytree(src, dst):
    
    from os import path, waitpid
    from subprocess import Popen, PIPE

    #Append any trailing / that we need to get rsync to work correctly.
    source = path.join(src, "")
    desti = path.join(dst, "")
    if not path.isdir(desti):
        from os import mkdir
        mkdir(desti)
    
    prsync = Popen("rsync -t -u -r {} {}".format(source, desti), close_fds=True,
                    shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE)
    waitpid(prsync.pid, 0)
    #Redirect the output and errors so that we don't pollute stdout.
    #output = prsync.stdout.readlines()
    error = prsync.stderr.readlines()
    prsync.stderr.close()
    prsync.stdout.close()

    if len(error) > 0:
        from fortpy.msg import warn
        warn("Error while copying {} using rsync.\n\n{}".format(source, '\n'.join(error)))
1218017
def make_nucsat(relname, nuc_types, elements):
    
    assert len(elements) == 2 and len(nuc_types) == 2, \
        "A nucsat relation must have two elements."
    assert set(nuc_types) == set(['N', 'S']), \
        "A nucsat relation must consist of one nucleus and one satellite."
 
    result = "\dirrel"
    for i, nuc_type in enumerate(nuc_types):
        if nuc_type == 'N':
            result += '\n\t' + NUC_TEMPLATE.substitute(nucleus=elements[i])    
        else:
            result += '\n\t' + SAT_TEMPLATE.substitute(satellite=elements[i], relation=relname)
    return result
337361
def sugartex_preprocess(source: str) -> str:
    
    rep = {r'\ˎ': 'ˎ', 'ˎ': '$'}
    return re.sub(r'\\ˎ|ˎ', lambda m: rep[m.group(0)], source)
1058172
def gen_rst(results):
    

    # make sure the destination directory exists
    try:
        os.mkdir(DOCPATH)
    except OSError as e:
        if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
            raise

    toctree = []
    class_ = []
    for output in results:
        section = output.class_.split(',')
        for i in range(len(section)):
            section[i] = section[i].rstrip()
            if section[i] in CLASSMAP:
                section[i] = CLASSMAP[section[i]]
            if i >= len(class_) or section[i] != class_[i]:
                if i == 0:
                    filename = section[i].replace(' ', '_').lower()
                    rst = open(DOCPATH + filename + '.rst', 'w')
                    rst.write(HEADER)
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[0] * len(section[i]))
                    rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
                    toctree.append(filename)
                else:
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i]))
                    rst.write('\n\n')
        class_ = section
        rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0])
        rst.write(output.desc + '\n')
        rst.write('~' * len(output.desc) + '\n\n')
        if output.cause != 'Unknown':
            rst.write('**Cause:** ' + output.cause + '\n\n')
        if output.workaround != 'Unknown':
            rst.write('**Workaround:** ' + output.workaround + '\n\n')

        rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n')
        output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip()
        output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy
        output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip()
        output_upy = ('::\n\n' if output_upy != '' else '') + output_upy
        table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]])
        rst.write(table)

    template = open(INDEXTEMPLATE, 'r')
    index = open(DOCPATH + INDEX, 'w')
    index.write(HEADER)
    index.write(template.read())
    for section in INDEXPRIORITY:
        if section in toctree:
            index.write(indent(section + '.rst', TAB))
            toctree.remove(section)
    for section in toctree:
        index.write(indent(section + '.rst', TAB))
1165349
def serialize_symbol(ctx, document, el, root):
    ""

    span = etree.SubElement(root, 'span')
    span.text = el.value()

    fire_hooks(ctx, document, el, span, ctx.get_hook('symbol'))

    return root
750408
def copy_tree(src, dst, symlinks=False, ignore=[]):
    
    names = os.listdir(src)

    if not os.path.exists(dst):
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignore:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copy_tree(srcname, dstname, symlinks, ignore)
            else:
                copy_file(srcname, dstname)
        except (IOError, os.error) as exc:
            errors.append((srcname, dstname, str(exc)))
        except CTError as exc:
            errors.extend(exc.errors)
    if errors:
        raise CTError(errors)