create a unique signature for any GFF line based on joining
        columns 1,2,3,4,5,7,8 (into a comma separated string)
356469
def signature(self):
        
        sig_elems = [self.seqid, self.source, self.type, \
                    self.start, self.end, self.strand, \
                    self.phase]
        if re.search("exon|CDS|UTR", self.type):
            parent = self.get_attr("Parent")
            if parent:
                (locus, iso) = atg_name(parent, retval="locus,iso", \
                        trimpad0=False)
                if locus:
                    sig_elems.append(locus)
        else:
            sig_elems.extend([self.accn])

        return ",".join(str(elem) for elem in sig_elems)
1070612
def create_col_nums():
    
    NUM_REPEATS = 2
    column_letters = list(
        string.ascii_uppercase
    ) + map(
        ''.join,
        itertools.product(
            string.ascii_uppercase,
            repeat=NUM_REPEATS
        )
    )
    letter_numbers = []

    count = 1
    for letter in column_letters:
        letter_numbers.append((count, str(count) + ' (' + letter + ')'))
        count += 1

    return tuple(letter_numbers)
333876
private static String concat(Collection<String> col)
	{
		StringBuilder b = new StringBuilder();
		boolean first = true;
		for (String s : col)
		{
			if (first)
				first = false;
			else
				b.append(";");

			b.append(s);
		}
		return b.toString();
	}
800676
public static <T> String join(Collection<T> col, String delim) {
    StringBuilder sb = new StringBuilder();
    Iterator<T> iter = col.iterator();
    if (iter.hasNext())
      sb.append(iter.next().toString());
    while (iter.hasNext()) {
      sb.append(delim);
      sb.append(iter.next().toString());
    }
    return sb.toString();
  }
813016
def sigStrToKwArgsDict(checkFuncSig):
    
    p1 = checkFuncSig.find('(')
    p2 = checkFuncSig.rfind(')')
    assert p1 > 0 and p2 > 0 and p2 > p1, "Invalid signature: "+checkFuncSig
    argParts = irafutils.csvSplit(checkFuncSig[p1+1:p2], ',', True)
    argParts = [x.strip() for x in argParts]
    retval = {}
    for argPair in argParts:
        argSpl = argPair.split('=', 1)
        if len(argSpl) > 1:
            if argSpl[0] in retval:
                if isinstance(retval[argSpl[0]], (list,tuple)):
                    retval[argSpl[0]]+=(irafutils.stripQuotes(argSpl[1]),) # 3rd
                else: # 2nd in, so convert to tuple
                    retval[argSpl[0]] = (retval[argSpl[0]],
                                         irafutils.stripQuotes(argSpl[1]),)
            else:
                retval[argSpl[0]] = irafutils.stripQuotes(argSpl[1]) # 1st in
        else:
            retval[argSpl[0]] = None #  eg. found "triggers=, max=6, ..."
    return retval
228589
def _filter_seqs(fn):
    """"""
    out_file = op.splitext(fn)[0] + "_unique.fa"
    idx = 0
    if not file_exists(out_file):
        with open(out_file, 'w') as out_handle:
            with open(fn) as in_handle:
                for line in in_handle:
                    if line.startswith("@") or line.startswith(">"):
                        fixed_name = _make_unique(line.strip(), idx)
                        seq = in_handle.next().strip()
                        counts = _get_freq(fixed_name)
                        if len(seq) < 26 and (counts > 1 or counts == 0):
                            idx += 1
                            print(fixed_name, file=out_handle, end="\n")
                            print(seq, file=out_handle, end="\n")
                        if line.startswith("@"):
                            in_handle.next()
                            in_handle.next()
    return out_file
24516
function(str, indent) {
			var lines = str.split("\n");
			for (var i=0; i<lines.length; i++)
				lines[i] = indent + lines[i];
			return lines.join("\n");
		}
1326606
def unique_list(input_list):
    
    """
    output_list = []
    if len(input_list) > 0:
        dim = _sp.shape(input_list)[1]
        for i in input_list:
            match = False
            for j in output_list:
                if dim == 3:
                    if i[0] == j[0] and i[1] == j[1] and i[2] == j[2]:
                        match = True
                elif dim == 2:
                    if i[0] == j[0] and i[1] == j[1]:
                        match = True
                elif dim == 1:
                    if i[0] == j[0]:
                        match = True
            if match is False:
                output_list.append(i)
    return output_list
263183
def add_function_signature_help(spec_dict: dict) -> dict:
    
    for f in spec_dict["functions"]["signatures"]:
        for argset_idx, argset in enumerate(spec_dict["functions"]["signatures"][f]["signatures"]):
            args_summary = ""
            args_list = []
            arg_idx = 0
            for arg_idx, arg in enumerate(
                spec_dict["functions"]["signatures"][f]["signatures"][argset_idx]["arguments"]
            ):
                if arg["type"] in ["Function", "Modifier"]:
                    vals = [
                        spec_dict["functions"]["to_short"].get(
                            val, spec_dict["functions"]["to_short"].get(val)
                        )
                        for val in arg["values"]
                    ]
                    args_summary += "|".join(vals) + "()"
                    arg_idx += 1

                    if arg.get("optional", False) and arg.get("multiple", False) is False:
                        args_summary += "?"
                        text = f'Zero or one of each function(s): {", ".join([val for val in arg["values"]])}'
                    elif arg.get("optional", False):
                        args_summary += "*"
                        text = f'Zero or more of each function(s): {", ".join([val for val in arg["values"]])}'
                    else:
                        text = f'One of following function(s): {", ".join([val for val in arg["values"]])}'

                elif arg["type"] in ["NSArg", "StrArg", "StrArgNSArg"]:
                    args_summary += f'{arg["type"]}'
                    if arg.get("optional", False) and arg.get("multiple", False) is False:
                        args_summary += "?"
                        if arg["type"] in ["NSArg"]:
                            text = f'Zero or one namespace argument of following type(s): {", ".join([val for val in arg["values"]])}'
                        elif arg["type"] == "StrArgNSArg":
                            text = f'Zero or one amespace argument or default namespace argument (without prefix) of following type(s): {", ".join([val for val in arg["values"]])}'
                        else:
                            text = f'Zero or one string argument of following type(s): {", ".join([val for val in arg["values"]])}'
                    elif arg.get("optional", False):
                        args_summary += "*"
                        if arg["type"] in ["NSArg"]:
                            text = f'Zero or more namespace arguments of following type(s): {", ".join([val for val in arg["values"]])}'
                        elif arg["type"] == "StrArgNSArg":
                            text = f'Zero or more namespace arguments or default namespace arguments (without prefix) of following type(s): {", ".join([val for val in arg["values"]])}'
                        else:
                            text = f'Zero or more of string arguments of following type(s): {", ".join([val for val in arg["values"]])}'
                    else:
                        if arg["type"] in ["NSArg"]:
                            text = f'Namespace argument of following type(s): {", ".join([val for val in arg["values"]])}'
                        elif arg["type"] == "StrArgNSArg":
                            text = f'Namespace argument or default namespace argument (without prefix) of following type(s): {", ".join([val for val in arg["values"]])}'
                        else:
                            text = f'String argument of following type(s): {", ".join([val for val in arg["values"]])}'

                args_summary += ", "
                args_list.append(text)

            args_summary = re.sub(", $", "", args_summary)
            spec_dict["functions"]["signatures"][f]["signatures"][argset_idx][
                "argument_summary"
            ] = f"{f}({args_summary})"
            spec_dict["functions"]["signatures"][f]["signatures"][argset_idx][
                "argument_help_listing"
            ] = args_list

            # print(f'{f}({args_summary})')
            # print(args_list)

    return spec_dict
132550
def make_signature(func):
    

    spec = inspect.getfullargspec(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for var, default in zip(spec.args, defaults):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.varkw:
        args.append('**' + spec.varkw)
    return args, spec.args
298387
def make_unique_ngrams(s, n):
    """"""
    return set(s[i:i + n] for i in range(len(s) - n + 1))
1012422
def format_op_row(ipFile, totLines, totWords, uniqueWords):
    
    txt = os.path.basename(ipFile).ljust(36) + ' '
    txt += str(totLines).rjust(7) + ' '
    txt += str(totWords).rjust(7) + ' '
    txt += str(len(uniqueWords)).rjust(7) + ' '
    return txt
128651
def unique_labels(line_labels):
    """"""
    from collections import defaultdict
    d = defaultdict(int)
    for i in line_labels:
        d[i] += 1
    d = dict((i, k) for i, k in d.items() if k != 1)
    line_labels_u = []
    for lab in reversed(line_labels):
        c = d.get(lab, 0)
        if c >= 1:
            v = lab + "_num_" + str(c)
            d[lab] -= 1
        else:
            v = lab
        line_labels_u.insert(0, v)

    return line_labels_u
395236
def to_one_line_string(tiles):
        
        tiles = sorted(tiles)

        man = [t for t in tiles if t < 36]

        pin = [t for t in tiles if 36 <= t < 72]
        pin = [t - 36 for t in pin]

        sou = [t for t in tiles if 72 <= t < 108]
        sou = [t - 72 for t in sou]

        honors = [t for t in tiles if t >= 108]
        honors = [t - 108 for t in honors]

        sou = sou and ''.join([str((i // 4) + 1) for i in sou]) + 's' or ''
        pin = pin and ''.join([str((i // 4) + 1) for i in pin]) + 'p' or ''
        man = man and ''.join([str((i // 4) + 1) for i in man]) + 'm' or ''
        honors = honors and ''.join([str((i // 4) + 1) for i in honors]) + 'z' or ''

        return man + pin + sou + honors
294265
def _join_chars(chars, length):
    
    mult = int(length / len(chars)) + 1
    mult_chars = chars * mult
    return "".join(random.sample(mult_chars, length))
306596
def make_fcn(filename):
    
    # collect lines and parse first several lines for fit info
    with open(filename, 'r') as ifile:
        lines = ifile.readlines()
    name = filename.split('.')[0]
    _certified_values = re.compile('.*Certified Values\s*\(lines\s*([0-9]*)\s*to\s*([0-9]*)\)')
    _data = re.compile('.*Data\s*\(lines\s*([0-9]*)\s*to\s*([0-9]*)\)')
    _model = re.compile('^Model:')
    values = None
    data = None
    fcn = None
    for i,line in enumerate(lines):
        m = _certified_values.match(line)
        if m is not None:
            values = (int(m.group(1)), int(m.group(2)))
        m = _data.match(line)
        if m is not None:
            data = (int(m.group(1)), int(m.group(2)))
        m = _model.match(line)
        if m is not None:
            fcn = ""
            for j in range(i+3,values[0] - 1):
                s = lines[j].strip()
                if s == '':
                    break
                fcn += s
        if None not in [values, data, fcn]:
            break
    # get rid of + e
    fcn = fcn[:-4]
    # fix [] brackets
    s = fcn.split('[')
    if len(s) > 1:
        _bracket = re.compile('(.*)\](.*)')
        nfcn = s[0]
        for si in s[1:]:
            m = _bracket.match(si)
            if m is not None:
                si = m.group(1) + ')' + m.group(2)
                si = '(' + m.group(1) + ')' + m.group(2)
            nfcn += si
        fcn = nfcn
    # parameter names
    nparam = values[1] - values[0] + 1 - 5
    pnames = ','.join(['b' + str(i+1) for i in range(nparam)])
    p = []
    p0 = []
    prior = []
    for i in range(values[0] - 1, values[0] - 1 + nparam):
        s = lines[i].split()
        p.append(gv.gvar(s[-2] + ' +- ' + s[-1]))
        if USE_2ND_STARTING_VALUE:
            p0.append(float(s[3]))
        else:
            p0.append(float(s[2]))
        prior.append(gv.gvar('0 +- ' + str(200 * p[-1].mean)))
    p = np.array(p)
    p0 = np.array(p0)
    prior = list(gv.fmt(prior))
    nistp = answers.get(name, str(p))
    # error on y
    s = lines[values[1] - 3].split()
    yerr = '0 +- ' + s[-1]
    # collect x, y
    x = []
    y = []
    for i in range(data[0] - 1, data[1]):
        s = lines[i].split()
        if len(s) == 2:
            x.append(float(s[-1]))
            y.append(float(s[-2]))
        elif len(s) > 2:
            y.append(float(s[0]))
            x.append([float(si) for si in s[1:]])
    x = np.array(x)
    if len(x.shape) > 1:
        xnames = ','.join(['x' + str(i+1) for i in range(x.shape[1])])
        x = x.T
    else:
        xnames = 'x'
    y = np.array(y)
    if len(nistp.split('\n')) > 1:
        nistp = '\\n'.join(nistp.split('\n'))
    if name == 'nelson':
        fcn = fcn.replace('log(y)', 'y')
        yname = 'log(y)'
    else:
        yname = 'y'
    if name == 'mgh10' and not USE_2ND_STARTING_VALUE:
        p0 = gv.sdev(gv.gvar(prior)) / 100.
    template = \
"""
def {name}():
    print(20 * '=', '{name}')
    x = np.{x}
    y = np.{y}
    y = {yname} + gv.gvar(len(y) * ['{yerr}'])
    def fcn(x, b):
        {xnames} = x
        {pnames} = b
        {fcn}
        return y
    prior = gv.gvar({prior})
    p0 = np.{p0}
    fit = lsqfit.nonlinear_fit(
        prior=prior, data=(x,y), fcn=fcn, p0=p0, tol=1e-10,
        )
    print(fit)
    assert str(fit.p) == '{nistp}'
"""
    return template.format(
        name=name,
        x=repr(x),
        y=repr(y),
        p0=repr(p0),
        yerr=yerr,
        fcn=fcn,
        prior=repr(prior),
        nistp=nistp,
        pnames=pnames,
        xnames=xnames,
        yname=yname,
        )
1005073
def _join_sequence(seq, last_separator=''):
    """"""
    count = len(seq)
    return ', '.join(_format_element(element, count, i, last_separator)
                     for i, element in enumerate(seq))