Beispiel #1
0
    def test_set(self):
        load_diet_model(self.ampl)
        ampl = self.ampl
        self.assertEqual(ampl.get_set("FOOD").to_string(), "set FOOD;")
        self.assertEqual(str(ampl.get_set("FOOD")), "set FOOD;")
        self.assertEqual(
            ampl.get_set("NUTR").size(),
            len(ampl.get_set("NUTR").members()),
        )
        self.assertEqual(
            len(ampl.get_set("NUTR").members()),
            len(list(ampl.get_set("NUTR").members())),
        )
        self.assertTrue(ampl.get_set("NUTR").contains("A"))
        self.assertTrue(ampl.get_set("NUTR").contains(("B1",)))
        self.assertFalse(ampl.get_set("NUTR").contains("X"))
        for _, st in ampl.get_sets():
            self.assertTrue(isinstance(st.arity(), int))
            self.assertEqual(st.arity(), 1)
            self.assertTrue(isinstance(st.size(), int))
            self.assertEqual(len(st.instances()), 1)
            self.assertEqual(len(dict(st.instances())), len(list(st.instances())))
            self.assertTrue(isinstance(st.arity(), int))
        ampl.eval("model; set T{1..2}; set T2{1..2};")
        ampl.get_set("T")[1] = [-1, -2]
        self.assertEqual(ampl.get_set("T").get((1,)).get_values().to_list(), [-1, -2])
        self.assertEqual(ampl.get_set("T").find((3,)), None)
        self.assertIsInstance(ampl.get_set("T").find(1), amplpy.Set)
        ampl.get_set("T")[1].set_values([1, 2])
        self.assertEqual(ampl.get_set("T")[1].get_values().to_list(), [1, 2])
        ampl.get_set("T")[2].set_values(["1", 2])
        self.assertEqual(ampl.get_set("T")[2].get_values().to_list(), ["1", 2])
        ampl.get_set("T2")[1].set_values(ampl.get_set("T")[1].get_values())
        self.assertEqual(ampl.get_set("T2")[1].get_values().to_list(), [1, 2])
        ampl.get_set("T2")[2].set_values(ampl.get_set("T")[2].get_values())
        self.assertEqual(ampl.get_set("T2")[2].get_values().to_list(), ["1", 2])
        ampl.eval("set T3 dimen 2; set T4 dimen 2;")
        ampl.get_set("T3").set_values([(1, 2)])
        self.assertEqual(ampl.get_set("T3").get_values().to_list(), [(1, 2)])
        ampl.get_set("T3").set_values(set([("b", 1), ("a", 2)]))
        self.assertEqual(
            sorted(ampl.get_set("T3").get_values().to_list()), [("a", 2), ("b", 1)]
        )
        ampl.eval("set T5;")
        ampl.set["T5"] = set(["a", "b", "c"])
        self.assertEqual(
            sorted(ampl.get_set("T5").get_values().to_list()), ["a", "b", "c"]
        )

        try:
            import numpy as np
        except ImportError:
            pass
        else:
            ampl.get_set("T")[1].set_values(np.array([1, 2]))
            self.assertEqual(ampl.get_set("T")[1].size(), 2)
            ampl.get_set("T3").set_values(np.array([[1, 2], [3, 4]]))
            self.assertEqual(ampl.get_set("T3").size(), 2)
def getRelPorts(att_stg, prod_dist, num=0):
    att_stg_sorted = sorted(att_stg.items(), key=lambda kv: kv[1])
    prod_dist_sorted = sorted(prod_dist.items(), key=lambda kv: kv[1])
    if num == 0:
        return list(set().union([x[0] for x in att_stg_sorted],
                                [x[0] for x in att_stg_sorted]))
    else:
        return list(set().union([x[0] for x in att_stg_sorted[-num:]],
                                [x[0] for x in att_stg_sorted[-num:]]))
Beispiel #3
0
 def nestedLists():
     students = []
     for _ in range(int(input())):
         name = input()
         score = float(input())
         students.append({'name': name, 'score': score})
     uniqueScores = sorted(set(map(lambda e: e['score'], students)))
     minScore = uniqueScores[0] if len(
         uniqueScores) == 1 else uniqueScores[1]
     [
         print(e['name']) for e in sorted(list(
             filter(lambda e: e['score'] == minScore, students)),
                                          key=lambda e: e['name'])
     ]
    def pass_a_freq(self, trades, liquidate):
        self.current_holding_cash = 0
        for name, positions in self.holdings.items():
            for position in positions:
                position.pass_a_freq(self.current_freq)
                self.current_holding_cash += position.curr_value

        if liquidate:
            self.liquidate_positions()
        else:
            self.close_positions()

        clean_trade = sorted(trades, key=lambda td: self.edge_no_limit(td), reverse=True)
        for trade in clean_trade:
            self.add_position(trade)

        self.pay_borrow_cost()

        capital_used = 0
        trade_hold = 0
        for name, positions in self.holdings.items():
            for position in positions:
                capital_used += position.initial_capital
                trade_hold += 1

        if liquidate and self.current_holding_cash != 0:
            raise Exception("should not be here")

        self.daily_status.append((self.current_freq, self.capital + self.current_holding_cash, self.capital, capital_used, trade_hold))
def build_alphabet(spectrum, m):
    """

    :param spectrum: an experimental spectrum
    :param m: the multiplicity threshold
    :return: a convolution spectrum, trimmed to contain only peptide masses appearing m times or more.
    """

    convolutions = dict()

    for i in range(0, len(spectrum)):
        for j in range(i + 1, len(spectrum)):
            diff = spectrum[j] - spectrum[i]
            if diff > 0 and 57 <= diff <= 200:
                if diff in convolutions.keys():
                    convolutions[diff] += 1
                else:
                    convolutions[diff] = 1

    sorted_list = sorted(convolutions.items(), key=operator.itemgetter(1), reverse=True)

    score_to_beat = sorted_list[m - 1][1]

    result = []

    for item in sorted_list:
        if item[1] >= score_to_beat:
            result.append(item[0])

    return result
Beispiel #6
0
async def sorted(
    iterable: AnyIterable[T],
    *,
    key: Optional[Callable[[T], Any]] = None,
    reverse: bool = False,
) -> List[T]:
    """
    Sort items from an (async) iterable into a new list

    The optional ``key`` argument specifies a one-argument (async) callable, which
    provides a substitute for determining the sort order of each item.
    The special value and default :py:data:`None` represents the identity functions,
    i.e. compares items directly.

    The default sort order is ascending, that is items with ``a < b``
    imply ``result.index(a) < result.index(b)``. Use ``reverse=True``
    for descending sort order.

    .. note::

        The actual sorting is synchronous,
        so a very large ``iterable`` or very slow comparison
        may block the event loop notably.
        It is guaranteed to be worst-case O(n log n) runtime.
    """
    if key is None:
        try:
            return _sync_builtins.sorted(iterable, reverse=reverse)
        except TypeError:
            pass
    key = _awaitify(key) if key is not None else _identity
    keyed_items = [(await key(item), item) async for item in aiter(iterable)]
    keyed_items.sort(key=lambda ki: ki[0], reverse=reverse)
    return [item for key, item in keyed_items]
Beispiel #7
0
def create_alerts_bloom_filters(n=41, p=0.05):
    """
    This method creates a bloom filter for each alert saved on the database.
    The bloom filters contain the conditions each alert is related to.

    :param n: number of items expected to be stored in filter for Bloom filters
    :param p: False Positive probability in decimal for Bloom Filters
    :return None
    """
    db = get_db_instance()
    condition_types = ["boolean", "integer"]
    alerts = [
        result for condition_type in condition_types
        for result in db.fetch_data(
            _alert_condition_query_generator(condition_type))
    ]

    sorted_alerts = sorted(alerts, key=lambda x: x.alert_id)

    prev_alert_id = None
    bf = BloomFilter(n, p)

    for alert in sorted_alerts:
        add_bloom_filter_rule(bf, alert.name, alert.value)

        if prev_alert_id != alert.alert_id and prev_alert_id is not None:
            save_bloom_filter_rule(alert.alert_id, bf)
            bf = BloomFilter(n, p)

        prev_alert_id = alert.alert_id
    def canny_edge(image_file, width, height):
        src = cv2.cvtColor(image_file, cv2.IMREAD_GRAYSCALE)
        #  apply Gaussian blur on src image
        blurred = cv2.GaussianBlur(image_file, (5, 5), cv2.BORDER_DEFAULT)

        #  apply canny edge detection to the blurred image
        edge = auto_canny(src)
        x = edge.copy()
        cnts = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)

        l, a, b = cv2.split(blurred)

        clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
        cl = clahe.apply(l)

        #-----Merge the CLAHE enhanced L-channel with the a and b channel-----------
        limg = cv2.merge((cl, a, b))

        #-----Converting image from LAB Color model to RGB model--------------------
        final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

        edge = auto_canny(final)
        x = edge.copy()
        cv2.drawContours(x, cnts, -1, (255, 0, 0), 5)
        cnts = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]
        k = np.zeros(shape=[height, width, 3], dtype=np.uint8)
        cv2.drawContours(k, [cnts[0]], -1, (255, 255, 255), 1)
        M = cv2.moments(cnts[0])
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        return k, [cX, cY]
def leaderboard_sequence(spectrum, n, alphabet):
    spectrum = sorted(spectrum)
    parent_mass = max(spectrum)
    leader_board = [[]]
    leader_peptide = []

    while len(leader_board) > 0:
        leader_board = expand(leader_board, alphabet)
        # copy for loop
        # leader_score = score(leader_peptide, spectrum)
        leader_score = 0
        temp = leader_board[:]
        for peptide in temp:
            mass = sum(peptide)
            if mass == parent_mass:
                s = cyc_score(peptide, spectrum)
                if s > leader_score:
                    leader_peptide = peptide
                    leader_score = s

            elif mass > parent_mass:
                leader_board.remove(peptide)

        leader_board = trim(leader_board, spectrum, n)

    return leader_peptide
Beispiel #10
0
 def testEnvironment(self):
     from amplpy import Environment, AMPL
     env1 = Environment()
     env2 = Environment(os.curdir)
     self.assertEqual(env2.getBinDir(), os.curdir)
     env1.setBinDir(env2.getBinDir())
     self.assertEqual(env1.getBinDir(), env1.getBinDir())
     self.assertEqual(len(dict(env1)), len(list(env1)))
     self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1)))
     env1['MyEnvVar'] = 'TEST'
     self.assertEqual(env1['MyEnvVar'], 'TEST')
     self.assertEqual(env2['MyEnvVar'], None)
     d = dict(env1)
     self.assertEqual(d['MyEnvVar'], 'TEST')
     ampl = AMPL(Environment())
     ampl.close()
Beispiel #11
0
    def run(self) -> None:
        ingester = FileIngester(self.file)
        docs = ingester.read()

        self.report["num_of_paragraphs"] = len(docs)

        clean_docs = self.clean_docs(docs)
        self.process_docs(clean_docs)
        # print(self.tf)
        self.report["num_unique_words"] = len(self.tf.keys())

        print(self.report)

        words = sorted(self.tf.items(), key=self.tf_compare, reverse=True)

        one_doc_words = self.calc_number_of_words_in_one_doc()

        percentage_one_doc_words = one_doc_words / self.report[
            "num_unique_words"]

        print("Number of words in only 1 document: {}".format(one_doc_words))
        print("Percentage of words in only 1 document: {}".format(
            percentage_one_doc_words))

        print("Top 100")
        self.print_results(words[0:100])
        print("Top 500th word")
        self.print_results(words[499:500])
        print("Top 1000th word")
        self.print_results(words[999:1000])
        print("Top 5000th word")
        self.print_results(words[4999:5000])
def sorted(colors, color_order='hSL', key=None, reverse=False):
    """Sort colors in the order specified by color_order.

    Sort colors given as a list or tuple of Color instances or hex
    color codes.  You can specify sorting order by giving a color_order
    string, such as "HSL" or "RGB".  A component of color_order on the
    left side has a higher sorting precedence, and an uppercase letter
    means descending order.
    :param colors: List of Color instances or items from which color
                   hex codes can be retrieved.
    :type colors: list or tuple
    :param color_order: String such as "HSL", "RGB" or "lsH" [optional]
    :type color_order: str
    :param key: Function used to retrive key values from items to be
                sorted [optional]
    :type key: function or None
    :param reverse: If set to True, reverse the sorting order [optional]
    :type reverse: bool
    :return: List of sorted colors.
    :rtype: list of Color
    """
    key_type = key_types.guess(colors[0], key)
    key_func = compile_sort_key_function(color_order, key_type, key)

    return builtins.sorted(colors, key=key_func, reverse=reverse)
Beispiel #13
0
def sorted(stack, stash):
    reverse, key, iterable = [pythonify(stack.pop()) for _ in range(3)]

    def new_key(el):
        stack.append(el)
        key(stack, stash)
        return stack.pop()
    stack.append(builtins.sorted(iterable, key=new_key, reverse=reverse))
Beispiel #14
0
    def test_environment(self):
        from amplpy import Environment, AMPL

        env1 = Environment()
        env2 = Environment(os.curdir)
        self.assertEqual(env2.get_bin_dir(), os.curdir)
        env1.set_bin_dir(env2.get_bin_dir())
        self.assertEqual(env1.get_bin_dir(), env1.get_bin_dir())
        self.assertEqual(len(dict(env1)), len(list(env1)))
        self.assertEqual(list(sorted(dict(env1).items())), list(sorted(env1)))
        env1["MyEnvVar"] = "TEST"
        self.assertEqual(env1["MyEnvVar"], "TEST")
        self.assertEqual(env2["MyEnvVar"], None)
        d = dict(env1)
        self.assertEqual(d["MyEnvVar"], "TEST")
        ampl = AMPL(Environment())
        ampl.close()
Beispiel #15
0
def sorted(processes: List[T],
           *,
           key: SortKey,
           reverse: bool = False) -> List[T]:
    """Return processes sorted.

    >>> processes = [
    ...     LocalRunningProcess(
    ...         pid="6239",
    ...         appname="pgbench",
    ...         database="pgbench",
    ...         user="******",
    ...         client="local",
    ...         cpu=0.1,
    ...         mem=0.993_254_939_413_836,
    ...         read=0.1,
    ...         write=0.282_725_318_098_656_75,
    ...         state="idle in transaction",
    ...         query="UPDATE pgbench_accounts SET abalance = abalance + 141 WHERE aid = 1932841;",
    ...         duration=0.1,
    ...         wait=False,
    ...         io_wait=False,
    ...         is_parallel_worker=False,
    ...     ),
    ...     LocalRunningProcess(
    ...         pid="6228",
    ...         appname="pgbench",
    ...         database="pgbench",
    ...         user="******",
    ...         client="local",
    ...         cpu=0.2,
    ...         mem=1.024_758_418_061_11,
    ...         read=0.2,
    ...         write=0.113_090_128_201_154_74,
    ...         state="active",
    ...         query="UPDATE pgbench_accounts SET abalance = abalance + 3062 WHERE aid = 7289374;",
    ...         duration=None,
    ...         wait=False,
    ...         io_wait=False,
    ...         is_parallel_worker=True,
    ...     ),
    ... ]

    >>> processes = sorted(processes, key=SortKey.cpu, reverse=True)
    >>> [p.pid for p in processes]
    ['6228', '6239']
    >>> processes = sorted(processes, key=SortKey.mem)
    >>> [p.pid for p in processes]
    ['6239', '6228']
    >>> processes = sorted(processes, key=SortKey.duration, reverse=True)
    >>> [p.pid for p in processes]
    ['6239', '6228']
    """
    return builtins.sorted(
        processes,
        key=lambda p: getattr(p, key.name) or 0,  # TODO: avoid getattr()
        reverse=reverse,
    )
Beispiel #16
0
def big_sort(unsorted):

    #     for i in range(0,len(unsorted)):
    #         max=i
    #         flag=0
    #         for j in range(i+1,len(unsorted)):
    #             if(len(unsorted[j])>len(unsorted[max])):
    #                 max=j
    #                 flag=1
    #             elif(len(unsorted[j])==len(unsorted[max])):
    #                 for k in range(0,len(unsorted[j])):
    #                     if(int(unsorted[j][k])>int(unsorted[max][k])):
    #                         max=j
    #                         flag=1
    #                     elif(unsorted[j][k]<unsorted[max][k]):
    #                         break
    #                     else:
    #                         continue
    #             else:
    #                 continue
    #         if(flag==1):
    #             unsorted[i],unsorted[max]=unsorted[max],unsorted[i]
    #     print(unsorted.reverse())
    #using the bucket sort method
    bucket = {}
    for i in unsorted:
        length = len(i)
        if not length in bucket:
            bucket[length] = []

        bucket[length].append(i)
    for key in sorted(bucket):
        for value in sorted(bucket[key]):
            print(value)
            pass
    #using the zip list
    us = []
    lengths = []
    for j in unsorted:
        us.append(j)
        lengths.append(len(j))
    biglist = zip(lengths, us)
    print(sorted(biglist))
    for k in sorted(biglist):
        print(k[1])
Beispiel #17
0
def get_all_prob_labels(classifier, text):
    prob_labels = {}
    prob_dist = classifier.prob_classify(text)
    for label in classifier.labels():
        prob_labels[label] = (round(prob_dist.prob(label), 5))
    dic_labels = sorted(prob_labels.items(),
                        key=operator.itemgetter(1),
                        reverse=True)
    return dic_labels
Beispiel #18
0
    def extract_solution(self, source, direction, target, flow_limit=inf):
        """Extract a vector packing solution form an arc-flow solution."""
        assert direction in ("<-", "->")
        assert self.flow is not None
        assert self.labels is not None
        flow = self.flow
        labels = self.labels
        adj = {u: [] for u in self.V}

        if direction == "<-":
            node_a, node_b = target, source
            for (u, v, i) in flow:
                adj[v].append((u, (u, v, i)))
        else:
            node_a, node_b = source, target
            for (u, v, i) in flow:
                adj[u].append((v, (u, v, i)))

        if node_a not in adj or node_b not in adj:
            return []

        solution = []

        def go(u, f, path):
            """Recursive function for flow extraction."""
            if f == 0:
                return
            if u == node_b:
                patt = []
                for arc in path:
                    flow[arc] -= f
                    patt += labels.get(arc, [])
                solution.append((f, patt))
            else:
                for v, arc in adj[u]:
                    # v != node_a to avoid cycles
                    if v != node_a and flow[arc] > 0:
                        ff = min(f, flow[arc])
                        go(v, ff, path+[arc])
                        f -= ff

        go(node_a, flow_limit, [])

        # group identical patterns
        rep = {}
        for (r, p) in solution:
            p = tuple(sorted(p, key=repr))
            if p not in rep:
                rep[p] = r
            else:
                rep[p] += r

        solution = []
        for p in rep:
            solution.append((rep[p], list(p)))

        return solution
Beispiel #19
0
 def transpose(name2fn):
     fn2names = defaultdict(list)
     for name, vlist in name2fn.items():
         for fn, i in vlist:
             fn2names[fn].append((name, i))
     for fn, vlist in fn2names.items():
         vlist = sorted(vlist, key=lambda x: x[1])
         fn2names[fn] = [name for name, i in vlist]
     return fn2names
Beispiel #20
0
def sorted(entries):
    """A convenience to sort a list of entries, using entry_sortkey().

    Args:
      entries: A list of directives.
    Returns:
      A sorted list of directives.
    """
    return builtins.sorted(entries, key=entry_sortkey)
Beispiel #21
0
    def extract_solution(self, source, direction, target, flow_limit=inf):
        """Extract a vector packing solution form an arc-flow solution."""
        assert direction in ("<-", "->")
        assert self.flow is not None
        assert self.labels is not None
        flow = self.flow
        labels = self.labels
        adj = {u: [] for u in self.V}

        if direction == "<-":
            node_a, node_b = target, source
            for (u, v, i) in flow:
                adj[v].append((u, (u, v, i)))
        else:
            node_a, node_b = source, target
            for (u, v, i) in flow:
                adj[u].append((v, (u, v, i)))

        if node_a not in adj or node_b not in adj:
            return []

        solution = []

        def go(u, f, path):
            """Recursive function for flow extraction."""
            if f == 0:
                return
            if u == node_b:
                patt = []
                for arc in path:
                    flow[arc] -= f
                    patt += labels.get(arc, [])
                solution.append((f, patt))
            else:
                for v, arc in adj[u]:
                    # v != node_a to avoid cycles
                    if v != node_a and flow[arc] > 0:
                        ff = min(f, flow[arc])
                        go(v, ff, path + [arc])
                        f -= ff

        go(node_a, flow_limit, [])

        # group identical patterns
        rep = {}
        for (r, p) in solution:
            p = tuple(sorted(p, key=repr))
            if p not in rep:
                rep[p] = r
            else:
                rep[p] += r

        solution = []
        for p in rep:
            solution.append((rep[p], list(p)))

        return solution
Beispiel #22
0
def generate_random_cnf(variable_count, clause_count):
    clauses = []

    for x in range(0, clause_count):
        abs_clause = sorted(random.sample(range(1, variable_count + 1), 3))
        clause = [add_sign(literal) for literal in abs_clause]
        clauses.append(clause)

    return clauses
Beispiel #23
0
def draw_graph(svg_file, V, A, show_labels=False, ignore=None, back=None,
               loss=None, graph_attrs=None, verbose=False):
    """Draw an arc-flow graph in .svg format."""
    from pygraphviz.agraph import AGraph
    if ignore is None:
        ignore = []
    if back is None:
        back = []
    if loss is None:
        loss = []
    elif not isinstance(loss, (tuple, list)):
        loss = [loss]
    g = AGraph(
        rankdir="LR", directed=True, bgcolor="white",
        ranksep="1.0", nodesep="0.10",
        strict=False
    )
    if graph_attrs is not None:
        for attr, value in graph_attrs.items():
            g.graph_attr[attr] = value
    g.node_attr["shape"] = "ellipse"
    g.node_attr["color"] = "black"
    g.node_attr["fontcolor"] = "black"
    g.node_attr["penwidth"] = "2.0"

    lbls = sorted(
        set(i for (u, v, i) in A if i not in loss),
        key=lambda lbl: (repr(type(lbl)), lbl)
    )

    colors = Colors.uniquecolors(len(lbls)+1, v=0.5, p=0.0)

    used = set()
    for (u, v, i) in A:
        if (u, v) in ignore:
            continue
        used.add(u)
        used.add(v)
        if (u, v) in back:
            u, v = v, u
            d = "back"
        else:
            d = "front"
        if i in loss:
            g.add_edge(u, v, color="black", style="dashed", penwidth=2, dir=d)
        else:
            lbl = str(i) if show_labels else ""
            color = colors[lbls.index(i) % len(colors)]
            g.add_edge(u, v, color=color, penwidth=2, label=lbl, dir=d)

    for v in V:
        if v not in used:
            g.add_node(v)

    g.draw(svg_file, format="svg", prog="dot")
    if verbose:
        print("SVG file '{0}' generated!".format(svg_file))
def main(argv=None):
    """
    :param argv: the command line args
    :return: nothing
    """
    if argv is None:
        argv = sys.argv

    # read file of kmers
    # create overlaps list
    # feed list in to eulerian path solver

    with open("quiz2.txt") as contents:
        kmers = [line.rstrip('\n').strip(' ') for line in contents]

    overlaps = og.find_overlaps(kmers[1:])

    with open("reconstruct-graph.txt", "w") as text_file:
        for key, value in overlaps.items():
            text_file.write(key + " -> " + ",".join(value) + "\n")

    with open("reconstruct-graph.txt") as contents:
        lines = [line.rstrip('\n') for line in contents]

    graph = ec.build_graph(lines)
    cycle = ec.find_cycle(graph)

    temp = []

    for node in cycle:
        temp.append(node.label)

    t2 = sorted(temp)
    t3 = sorted(kmers)

    print("\n".join(t2))
    print(".....")
    print("\n".join(t3))

    with open("reconstructed_path2.txt", "w") as text_file:
        for i in range(0, len(temp) - 1):
            text_file.write(temp[i][0])
        text_file.write(temp[i + 1])
Beispiel #25
0
def display_table(data, headers):
    view_data = []
    for item in sorted(data):
        view_item = []
        for header in headers:
            view_item.append(item.get(header))
        view_data.append(view_item)

    print("")
    print(tabulate.tabulate(view_data, headers, tablefmt='orgtbl'))
Beispiel #26
0
def completely_sorted(x):
    """Multi-dimensional container sort.

    If x is list of lists of ... of lists,
    then the argument is lexicographically sorted on all levels,
    starting from the bottom.
    """
    if isinstance(x, list):
        return sorted(completely_sorted(e) for e in x)
    else:
        return x
Beispiel #27
0
def main():
    import sys
    from builtins import map, int, list, range, sorted, input
    readline = sys.stdin.readline

    N, K = map(int, input().split())

    for _ in range(K):
        N = list(map(int, list(str(N))))

        g1 = sorted(N, reverse=True)
        g1 = ''.join(map(str, g1))
        g1 = int(g1)

        g2 = sorted(N)
        g2 = ''.join(map(str, g2))
        g2 = int(g2)

        N = g1 - g2

    print(N)
Beispiel #28
0
 def make_table(self, dna):
     fl = []
     dna = dna + "$"
     fl.append([dna[0], dna[-1]])
     print("???")
     print(len(dna) - 1)
     for i in range(len(dna) - 1):
         print(str(i) + "  " + str(fl[i]))
         dna = dna[1:] + dna[0:1]
         fl.append([dna[0], dna[-1]])
     print("OOOOOOOOOOOOOOOOOOOO")
     fl = sorted(fl, key=lambda x: x[0])
     return fl
Beispiel #29
0
    def sort(self: FrozenList[_TSourceSortable],
             reverse: bool = False) -> FrozenList[_TSourceSortable]:
        """Sort list directly.

        Returns a new sorted collection.

        Args:
            reverse: Sort in reversed order.

        Returns:
            A sorted list.
        """
        return FrozenList(builtins.sorted(self.value, reverse=reverse))
Beispiel #30
0
def group_package_identifiers_by_name(pilist, pkgmap=None) -> dict:
    out = pkgmap if pkgmap is not None else {}
    for pi in pilist:
        if not isinstance(pi, PackageIdentifier):
            raise ValueError()
        current_pilist = out.get(pi.name)
        if current_pilist is None:
            current_pilist = []
            out[pi.name] = current_pilist
        if pi not in current_pilist:
            current_pilist.append(pi)
    for pkgname in out:
        out[pkgname] = sorted(out[pkgname])
    return out
def canny_edge(image_file, width, height):
    src = cv2.cvtColor(image_file, cv2.IMREAD_GRAYSCALE)
    #  TODO: Like the threshold values for canny edge, we need
    #   to determine the kernel values for Gaussian blur
    #  apply Gaussian blur on src image

    # TODO: Implement findContours to get the outline of the object:
    #  https://www.pyimagesearch.com/2014/04/21/building-pokedex-python-finding-game-boy-screen-step-4-6/

    blurred = cv2.GaussianBlur(image_file, (5, 5), cv2.BORDER_DEFAULT)

    #  apply canny edge detection to the blurred image
    edge = auto_canny(src)
    x = edge.copy()
    cnts = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)

    l, a, b = cv2.split(blurred)

    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
    cl = clahe.apply(l)
    # cv2.imshow('CLAHE output', cl)

    # -----Merge the CLAHE enhanced L-channel with the a and b channel-----------
    limg = cv2.merge((cl, a, b))
    # cv2.imshow('limg', limg)

    # -----Converting image from LAB Color model to RGB model--------------------
    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

    # cv2.imshow('final', final)

    edge = auto_canny(final)
    x = edge.copy()
    cv2.drawContours(x, cnts, -1, (255, 0, 0), 5)
    # cv2.imshow("Contours", x)
    # cv2.waitKey(0)
    cnts = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]
    k = np.zeros(shape=[height, width, 3], dtype=np.uint8)
    # print("Contours: ", cnts)
    cv2.drawContours(k, [cnts[0]], -1, (255, 255, 255), 1)
    # cv2.imshow("Contours", k)
    # cv2.waitKey(0)
    M = cv2.moments(cnts[0])
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
    return k, [cX, cY]
  def all(
    self,
    year: int = None,
    month: int = None,
    sorted: bool = True,
    reverse: bool = False
  ) -> Iterable[datetime.date]:
    """
    Iterates over all days in the database, or the days matching the specified *year* and *month*.
    """

    _sort = (lambda x: builtins.sorted(x, reverse=reverse)) if sorted else (lambda x: x)
    for curr_year in [year] if year is not None else _sort(self.years()):
      for curr_month in [month] if month is not None else _sort(self.months(curr_year)):
        for curr_day in _sort(self.days(curr_year, curr_month)):
          yield datetime.date(curr_year, curr_month, curr_day)
Beispiel #33
0
    def sort_with(self,
                  func: Callable[[_TSource], Any],
                  reverse: bool = False) -> FrozenList[_TSource]:
        """Sort list with supplied function.

        Returns a new sorted collection.

        Args:
            func: The function to extract a comparison key from each element in list.
            reverse: Sort in reversed order.

        Returns:
            A sorted list.
        """
        return FrozenList(
            builtins.sorted(self.value, key=func, reverse=reverse))
    def sorted(self, keyfunc=None, reverse=False):
        # type: (Callable, bool) -> IterableWrapper
        """ Sort the iterable.

            .. warning::

                This will load the entire iterable in memory. Remember you
                can slice g() objects before you sort them. Also remember you
                can use callable in g() object slices, making it easy to start
                or stop iteration on a condition.

            Args:
                keyfunc: A callable that must accept the current element to
                         sort and return the object used to determine it's
                         position. Default to return the object itselt.
                reverse: If True, the iterable is sorted in the descending
                         order instead of ascending. Default is False.

            Returns:
                The sorted iterable.

            Example:

                >>> from ww import g
                >>> animals = ['dog', 'cat', 'zebra', 'monkey']
                >>> for animal in g(animals).sorted():
                ...     print(animal)
                cat
                dog
                monkey
                zebra
                >>> for animal in g(animals).sorted(reverse=True):
                ...     print(animal)
                zebra
                monkey
                dog
                cat
                >>> for animal in g(animals).sorted(lambda animal: animal[-1]):
                ...     print(animal)
                zebra
                dog
                cat
                monkey
        """
        # using builtins to avoid shadowing
        lst = builtins.sorted(self.iterator, key=keyfunc, reverse=reverse)
        return self.__class__(lst)
def linear_spectrum(peptide):
    """
    :param peptide: string representation of a peptide
    :return: integer linear spectrum as a list of int
    """

    prefix_mass = [0]

    for i in range(0, len(peptide)):
        prefix_mass.append(prefix_mass[i] + peptide[i])

    linear_spectrum = []
    for i in range(0, len(peptide)):
        for j in range(i + 1, len(peptide) + 1):
            linear_spectrum.append(prefix_mass[j] - prefix_mass[i])

    return sorted(linear_spectrum)
def trim(leader_board, spectrum, n):
    if len(leader_board) > n:
        leader_scores = []
        for peptide in leader_board:
            leader_scores.append((lin_score(peptide, spectrum), peptide))

        leader_scores = sorted(leader_scores, key=operator.itemgetter(0), reverse=True)
        nth_score = leader_scores[n - 1][0]

        temp = []
        for i in range(0, len(leader_scores)):
            if leader_scores[i][0] >= nth_score:
                temp.append(leader_scores[i][1])

        leader_board = temp

    return leader_board
Beispiel #37
0
    def to_file(self, f, sorted=True, relativize=True, nl=None):
        """Write a zone to a file.

        @param f: file or string.  If I{f} is a string, it is treated
        as the name of a file to open.
        @param sorted: if True, the file will be written with the
        names sorted in DNSSEC order from least to greatest.  Otherwise
        the names will be written in whatever order they happen to have
        in the zone's dictionary.
        @param relativize: if True, domain names in the output will be
        relativized to the zone's origin (if possible).
        @type relativize: bool
        @param nl: The end of line string.  If not specified, the
        output will use the platform's native end-of-line marker (i.e.
        LF on POSIX, CRLF on Windows, CR on Macintosh).
        @type nl: string or None
        """

        if nl is None:
            opts = 'w'
        else:
            opts = 'wb'
        if isinstance(f, str):
            f = open(f, opts)
            want_close = True
        else:
            want_close = False
        try:
            if sorted:
                names = builtins.sorted(self.keys())
            else:
                names = self.keys()
            for n in names:
                l = self[n].to_text(n,
                                    origin=self.origin,
                                    relativize=relativize)
                if nl is None:
                    print(l, file=f)
                else:
                    f.write(l.encode('ascii'))
                    f.write(nl.encode('ascii'))
        finally:
            if want_close:
                f.close()
    def to_file(self, f, sorted=True, relativize=True, nl=None):
        """Write a zone to a file.

        @param f: file or string.  If I{f} is a string, it is treated
        as the name of a file to open.
        @param sorted: if True, the file will be written with the
        names sorted in DNSSEC order from least to greatest.  Otherwise
        the names will be written in whatever order they happen to have
        in the zone's dictionary.
        @param relativize: if True, domain names in the output will be
        relativized to the zone's origin (if possible).
        @type relativize: bool
        @param nl: The end of line string.  If not specified, the
        output will use the platform's native end-of-line marker (i.e.
        LF on POSIX, CRLF on Windows, CR on Macintosh).
        @type nl: string or None
        """

        if nl is None:
            opts = 'w'
        else:
            opts = 'wb'
        if isinstance(f, str):
            f = open(f, opts)
            want_close = True
        else:
            want_close = False
        try:
            if sorted:
                names = builtins.sorted(self.keys())
            else:
                names = self.keys()
            for n in names:
                l = self[n].to_text(n, origin=self.origin,
                                    relativize=relativize)
                if nl is None:
                    print(l, file=f)
                else:
                    f.write(l.encode('ascii'))
                    f.write(nl.encode('ascii'))
        finally:
            if want_close:
                f.close()
Beispiel #39
0
    def getNearestUser(self, username):
        """
        计算所有用户和 username 用户的距离,
        倒序排列并返回结果列表
        """
        result = []
        for user in self.users:
            if user != username:
                distance = self.calc_manhattan(users[user], users[username])
                result.append((user, distance))
        # result.reverse() # 倒序
        # result.sort()  # 正序
        # sorted 可以使用内部元素排序
        #  reverse = True  降序 或者 reverse = False 升序
        result = sorted(result, key=lambda x: x[1], reverse=True)

        # 多级排序 operator 函数进行多级排序 
        # result = sorted(result, key=itemgetter(1, 0), reverse=True)

        return result
Beispiel #40
0
def main(argv=None):
    """
    :param argv: the command line args
    :return: nothing
    """
    if argv is None:
        argv = sys.argv

    k = 12
    seq = "GCCCCCGCGGGGTAGTCCCCAGTAACATTCTAAGCTAGGGCTCGGCCCAAGCTACAAGGAGAAACACTATAGTGTAGGCGAGGATTGTCATGACACAACTGGTGAAAGTCATACCTCTTCCGCTTCTTAACCGGCGGCATCAGAGAAAAGTATAACGAACCTAAAGTTGAACACTCCGTTTCAGTGACCACGAGTTGTACCCGTTGTGTTATGGCCCGACGCTGGTTGATGGCTCCCTGACCTTTGTCAACAGCCCCCTGCATATTATATGAGGGCATCATGTAAGCGTTCCACTTGAACACGATGCGCACACCCTGTCCAAAAGTGTGAACGGCACTTGATAATCACGCGGGATACTCCTATCTGCACAACTTGAGGAGAAGGGCTTCCCGTCGCTCGACGACAATCCATGCTGGCTAACAGGTCCGTACCATATGTTGAAATGCGAAGGTTCTCGGTGGTGCCGCTCCACTTCAGCATGTACTGGTATGAGCTTGGTGAGTCATGGAAGCTCGATTCTTATACTCCCATGGGTGCTCGGCGGTCCACACATCGCATATGGCCCCAGGGGATGGATGAAACGTTGAGCGTTTTAGAACATGACATAAGGGAGGTGATTTACCCCACCCACCAACGAGCGATTCATCTTACGCCGACTGCACAGCCACGGTATCTACCGCTACGATGCAAACCTTTCTATTATCCTACTGGCGTCAGCCACTGCGCGTTGGTTTGGTGATAATTTGGACCGTACGGACTCTACCAAGGAGCCATGCTGAGCAGTCCAGTTGTATCTTCGATTGAAGATCAAGGTCGCAGCATCATGGTACGAGGGTGACTTCCTGGTGGCCCCGCGATTGAGATCCAGTCCCCGTTGCCATACCACTACGCACACCACTTGGTGTTAAGCGAAACCCTTCGCGCATTGTCCTCCATTGTCTGAGTGGATGCGCTAAATTAACTTCTACGTGGACAATGGTGCAGCGTACTGTCCATGGCGATTCGTACAGGAGTGGTGTTTGAACAGCTCTGGAGCGAAGTGAGAAGTGGTGTGGCGGCTCCCGGTCGTGGAGTCGCCGGAGACTTCTTATTTCACGTACTGTAAATAATGATCGCCCTAATTCGGCGCCCACCCTCGTGCCCCGCCCCTGCTGATTTTCGTCACATGGCGCGTGCTAACCCACATTTTGCGTCCTGGCTTGTTAGTCCCTGGATCCCCAAAAAATAATCTCCGCTGACTACTGTTTTGGACGGAAAACGAGGATCAGTAAACAGGTGTGAGCATCACGGTGCGTAAGACGTTACAACACCTTCGTTGTGGTTCTATTTACTGTGGTCCATCCGGAGAACCGAATCACGTAGTGCGAATCTGTTGCCTCTAGTCGACCATGACAGTTTCCCTAACATGCGTGACGGGACATGAACGGAGGACACTCTTTGTTCTTAATAGTTCTGTAACCCAACCTGTTGTTAGTGGGAGTACCAAAGATGATGTACAGAGAACCAGCATAGATGTTACACGACTACCTCACGGGTTAGTACGTATGGGCTTGAAAGATTGTTTTTTAGGTAGTCATGTGGTCTTTTTAGATCATGGACAGTCGCCCATAGACTCCTGCTAGGGGCCGCGGTAATTCTCCGCCCTGAACCGGTCCCTCCTTAGCCCCCAGGGGCGGCCGGGTCCAGTGTGGCAAGACCTTTTTCAAGTCCTGCCTATGGCCACGGCGAGATCCTATTATATGTACTTAAACATCGTTTAGAGTTCCCTACGTCTCACGATTCGAGTCTCGGGCTTCCCGCAGCACGCTACCTACTCCTGCACGCCTGTCTCACATTAGAACACGTCAGGTTGGATGTTTGGTCGGGAACTGCCGTACACTACCCACCTTCGTTGACTCTTGGCGAATTATCGCGTCATGATTTCCCTAAACTTGGTTTTTGGTTAACTTAGCTATCTCAACTAGATATTTTCGAAGCCTGCTCGCCCCACATCCCAAATG"

    with open("kmers.txt") as contents:
        kmers = [line.rstrip('\n') for line in contents]

    # for s in SequenceUtils.each_kmer(seq, k):
    # kmers.append(s)

    result = build_debruijn_graph(kmers)

    with open("debruijn.txt", "w") as text_file:
        for key, value in sorted(result.items()):
            text_file.write(key + " -> " + ",".join(value) + "\n")
def cyclic_spectrum(peptide):
    """
    :param peptide: string representation of a peptide
    :return: integer cyclic spectrum as a list of int
    """

    prefix_mass = [0]

    for i in range(0, len(peptide)):
        prefix_mass.append(prefix_mass[i] + peptide[i])

    peptide_mass = prefix_mass[len(peptide)]

    cyclic_spectrum = []
    for i in range(0, len(peptide)):
        for j in range(i + 1, len(peptide) + 1):
            cyclic_spectrum.append(prefix_mass[j] - prefix_mass[i])
            # do wrap arounds
            if i > 0 and j < len(peptide):
                cyclic_spectrum.append(peptide_mass - (prefix_mass[j] - prefix_mass[i]))

    return sorted(cyclic_spectrum)
Beispiel #42
0
 def history(self, oldest=None, latest=None, user=None, count=1000):
     def get_history_unpage(latest, oldest, count):
         res = self.endpoint.history(
             self.data["id"],
             count=count,
             latest=latest,
             oldest=oldest,
         ).body
         messages = res["messages"]
         if res["has_more"]:
             messages += get_history_unpage(latest=messages[-1]["ts"],
                                            oldest=oldest,
                                            count=count,
             )
         return messages
     return builtins.sorted([
         Message(message)
         for message in get_history_unpage(
                 oldest=oldest, latest=latest,
                 count=count
         )
         if not user or message.get("user") == user.id
     ])
Beispiel #43
0
def sort_vertices(V, reverse=False):
    """Return the list of vertices sorted."""
    return sorted(V, key=lambda k: (repr(type(k)), k), reverse=reverse)
def do_string_composition(k, seq):
    result = []
    for s in SequenceUtils.each_kmer(seq, k):
        result.append(s)

    return sorted(result)
Beispiel #45
0
Datei: t.py Projekt: nvbn/mcoll
def sorted(key, coll):
    return builtins.sorted(coll, key=key)
Beispiel #46
0
def sort_arcs(A, reverse=False):
    """Return the list of arcs sorted."""
    return sorted(
        A, key=lambda a: tuple((repr(type(k)), k) for k in a), reverse=reverse
    )
Beispiel #47
0
 def members_fmt(self):
     return ", ".join(
         builtins.sorted(
             config.slack.users[u]["name"] for u in self.members
         )
     )