Python functools.cmp_to_key() Examples

The following are 30 code examples of functools.cmp_to_key(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module functools , or try the search function .
Example #1
Source File: misc.py    From verge3d-blender-addon with GNU General Public License v3.0 7 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example #2
Source File: migration_tool.py    From indy-node with Apache License 2.0 6 votes vote down vote up
def _get_relevant_migrations(migration_scripts, current_version, new_version):
    relevant_migrations = []
    for migration in migration_scripts:
        migration_original_version, migration_new_version = _get_migration_versions(
            migration)
        if not migration_original_version or not migration_new_version:
            continue

        if Upgrader.compareVersions(new_version, current_version) >= 0:
            if Upgrader.compareVersions(
                    migration_original_version, migration_new_version) > 0:
                continue
            if Upgrader.compareVersions(current_version, migration_original_version) <= 0 \
                    and Upgrader.compareVersions(new_version, migration_new_version) >= 0:
                relevant_migrations.append(migration)
        else:
            if Upgrader.compareVersions(
                    migration_new_version, migration_original_version) > 0:
                continue
            if Upgrader.compareVersions(current_version, migration_original_version) >= 0 \
                    and Upgrader.compareVersions(new_version, migration_new_version) <= 0:
                relevant_migrations.append(migration)
        relevant_migrations = sorted(
            relevant_migrations, key=cmp_to_key(_compare_migration_scripts))
    return relevant_migrations 
Example #3
Source File: lib_tracker.py    From Realtime-Action-Recognition with MIT License 6 votes vote down vote up
def _sort_skeletons_by_dist_to_center(self, skeletons):
        ''' Skeletons are sorted based on the distance
        between neck and image center, from small to large.
        A skeleton near center will be processed first and be given a smaller human id.
        Here the center is defined as (0.5, 0.5), although it's not accurate due to h_scale.
        '''
        def calc_dist(p1, p2): return (
            (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5

        def cost(skeleton):
            x1, y1 = self._get_neck(skeleton)
            return calc_dist((x1, y1), (0.5, 0.5))  # dist to center

        def cmp(a, b): return (a > b)-(a < b)
        def mycmp(sk1, sk2): return cmp(cost(sk1), cost(sk2))
        sorted_skeletons = sorted(skeletons, key=functools.cmp_to_key(mycmp))
        return sorted_skeletons 
Example #4
Source File: PEMInserts.py    From FreeCAD_FastenersWB with GNU General Public License v2.0 6 votes vote down vote up
def soGetAllLengths(diam, blind):
  if blind:
    lmin, lmax = (6, 25)
  else:
    b, c, h, d, lmin, lmax = SOPEMTable[diam]
  list = []
  for len in SOLengths:
    l = float(len)
    if l >= lmin and l <= lmax:
      list.append(len)
  try:  # py3
    import functools
    sorted(list, key = functools.cmp_to_key(FastenerBase.NumCompare))
  except:
    list.sort(cmp = FastenerBase.NumCompare)
  return list

# h = clMakePressNut('M5','1') 
Example #5
Source File: topology_mapper.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def link_names(self):
        '''OrderedSet of link names (L#).'''
        try:
            from pyats.tcl.internal import DictionaryCompare
            topo_devices = list(self.devices.values())
            topo_links = set()
            for topo_dev in topo_devices:
                topo_links |= set(topo_dev.links)
            sLs = [topo_link.link_name for topo_link in topo_links]
            sLs = OrderedSet(sorted(sLs, key=functools.cmp_to_key(DictionaryCompare)))
            return sLs
        except ImportError:
            # Considering users with no sourced tcl environment
            pass
        except Exception:
            return 
Example #6
Source File: misc.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example #7
Source File: utils_disk.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def mount_all(self):
        def compare(a, b):
            if len(a[0]) > len(b[0]):
                return 1
            elif len(a[0]) == len(b[0]):
                return 0
            else:
                return -1

        roots = self.os_inspects()
        if roots:
            for root in roots:
                mps = self.g.inspect_get_mountpoints(root)
                mps.sort(key=cmp_to_key(compare))
                for mp_dev in mps:
                    try:
                        msg = "Mount dev '%s' partitions '%s' to '%s'"
                        logging.info(msg % (root, mp_dev[1], mp_dev[0]))
                        self.g.mount(mp_dev[1], mp_dev[0])
                    except RuntimeError as err_msg:
                        logging.info("%s (ignored)" % err_msg)
        else:
            raise exceptions.TestError(
                "inspect_vm: no operating systems found") 
Example #8
Source File: test_sort.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_undetected_mutation(self):
        # Python 2.4a1 did not always detect mutation
        memorywaster = []
        for i in range(20):
            def mutating_cmp(x, y):
                L.append(3)
                L.pop()
                return (x > y) - (x < y)
            L = [1,2]
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            def mutating_cmp(x, y):
                L.append(3)
                del L[:]
                return (x > y) - (x < y)
            self.assertRaises(ValueError, L.sort, key=cmp_to_key(mutating_cmp))
            memorywaster = [memorywaster]

#============================================================================== 
Example #9
Source File: test_sort.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_reverse_stability(self):
        data = [(random.randrange(100), i) for i in range(200)]
        copy1 = data[:]
        copy2 = data[:]
        def my_cmp(x, y):
            x0, y0 = x[0], y[0]
            return (x0 > y0) - (x0 < y0)
        def my_cmp_reversed(x, y):
            x0, y0 = x[0], y[0]
            return (y0 > x0) - (y0 < x0)
        data.sort(key=cmp_to_key(my_cmp), reverse=True)
        copy1.sort(key=cmp_to_key(my_cmp_reversed))
        self.assertEqual(data, copy1)
        copy2.sort(key=lambda x: x[0], reverse=True)
        self.assertEqual(data, copy2)

#============================================================================== 
Example #10
Source File: loader.py    From Imogen with MIT License 6 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def shouldIncludeMethod(attrname):
            if not attrname.startswith(self.testMethodPrefix):
                return False
            testFunc = getattr(testCaseClass, attrname)
            if not callable(testFunc):
                return False
            fullName = '%s.%s' % (testCaseClass.__module__, testFunc.__qualname__)
            return self.testNamePatterns is None or \
                any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)
        testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        return testFnNames 
Example #11
Source File: main.py    From schema.data.gouv.fr with MIT License 6 votes vote down vote up
def tags(self):
        if self.git_repo is None or len(self.git_repo.tags) == 0:
            raise exceptions.NoTagsException(self, "Cannot find tags")

        # Build a list of valid version names only.
        # Raise an exception only if the most recent
        # version name is invalid.
        versions = []
        for tag in self.git_repo.tags:
            try:
                versions.append(self.parse_version(tag.name))
            except exceptions.InvalidVersionException as e:
                if tag == self.git_repo.tags[-1]:
                    raise e

        return sorted(versions, key=cmp_to_key(SemverCmp)) 
Example #12
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example #13
Source File: misc.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
        def __hash__(self):
            raise TypeError('hash not implemented')
    return K

# Back up our definitions above in case they're useful 
Example #14
Source File: pstats.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], int):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example #15
Source File: barcharts.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, cmp=None):
        self._data = []
        self._key = functools.cmp_to_key(cmp) 
Example #16
Source File: test_sort.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def check(tag, expected, raw, compare=None):
    global nerrors

    if verbose:
        print("    checking", tag)

    orig = raw[:]   # save input in case of error
    if compare:
        raw.sort(key=cmp_to_key(compare))
    else:
        raw.sort()

    if len(expected) != len(raw):
        print("error in", tag)
        print("length mismatch;", len(expected), len(raw))
        print(expected)
        print(orig)
        print(raw)
        nerrors += 1
        return

    for i, good in enumerate(expected):
        maybe = raw[i]
        if good is not maybe:
            print("error in", tag)
            print("out of order at index", i, good, maybe)
            print(expected)
            print(orig)
            print(raw)
            nerrors += 1
            return 
Example #17
Source File: generator.py    From repository.castagnait with GNU General Public License v2.0 5 votes vote down vote up
def get_previous_addon_xml_ver(self, addon_folder_name, num_of_previous_ver):
        addon_xmls = []
        index = 0
        from functools import cmp_to_key
        folder_items = sorted(os.listdir(os.path.join(ZIP_FOLDER, addon_folder_name)),
                              key=cmp_to_key(self._file_compare_version), reverse=True)
        for item in folder_items:
            if index == num_of_previous_ver:
                break
            if item.endswith('.zip'):
                with ZipFile(os.path.join(ZIP_FOLDER, addon_folder_name, item), mode='r') as zip_obj:
                    addon_xmls += [zip_obj.read(addon_folder_name + '/addon.xml').decode('utf-8')]
                index += 1
        print('Added to addons.xml also {} of previous {} add-on version'.format(index, addon_folder_name))
        return addon_xmls 
Example #18
Source File: PEMInserts.py    From FreeCAD_FastenersWB with GNU General Public License v2.0 5 votes vote down vote up
def psGetAllLengths(mtable, ltable, diam, width):
  if not(diam in mtable):
    return None
  lenKey = diam + "x" + width
  if not(lenKey in ltable):
    return None
  list = ltable[lenKey]
  try:  # py3
    import functools
    sorted(list, key = functools.cmp_to_key(FastenerBase.NumCompare))
  except:
    list.sort(cmp = FastenerBase.NumCompare)
  return list

# h = clMakePressNut('M5','1') 
Example #19
Source File: PEMInserts.py    From FreeCAD_FastenersWB with GNU General Public License v2.0 5 votes vote down vote up
def psGetAllWidths(mtable, diam):
  if not(diam in mtable):
    return None
  list = mtable[diam][2]
  try:  # py3
    import functools
    sorted(list, key = functools.cmp_to_key(FastenerBase.NumCompare))
  except:
    list.sort(cmp = FastenerBase.NumCompare)
  return list 
Example #20
Source File: pstats.py    From Imogen with MIT License 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], int):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]
        elif len(field) >= 2:
            for arg in field[1:]:
                if type(arg) != type(field[0]):
                    raise TypeError("Can't have mixed argument type")

        sort_arg_defs = self.get_sort_arg_defs()

        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            if isinstance(word, SortKey):
                word = word.value
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.items():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example #21
Source File: label.py    From autowebcompat with Mozilla Public License 2.0 5 votes vote down vote up
def group_images():
    global images_to_show
    sorted_images_to_show = sorted(images_to_show, key=functools.cmp_to_key(images_cmp))
    if args.verify:
        bug_ids = OrderedDict.fromkeys([utils.parse_file_name(file_name)['bug_id'] for file_name in images_to_show])
    else:
        bug_ids = OrderedDict.fromkeys([utils.parse_file_name(file_name)['bug_id'] for file_name in images_not_in_all_labels + images_in_all_labels])
    images_to_show = [file_name for bug_id in bug_ids for file_name in sorted_images_to_show if bug_id == utils.parse_file_name(file_name)['bug_id']] 
Example #22
Source File: PEMInserts.py    From FreeCAD_FastenersWB with GNU General Public License v2.0 5 votes vote down vote up
def fhGetAllLengths(diam):
  h, s, d, lmin, lmax = FHPEMTable[diam]
  list = []
  for len in FHLengths:
    l = float(len)
    if l >= lmin and l <= lmax:
      list.append(len)
  try:  # py3
    import functools
    sorted(list, key = functools.cmp_to_key(FastenerBase.NumCompare))
  except:
    list.sort(cmp = FastenerBase.NumCompare)
  return list 
Example #23
Source File: veritesting.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_all_merge_points(self, cfg, graph_with_loops):
        """
        Return all possible merge points in this CFG.

        :param CFGEmulated cfg: The control flow graph, which must be acyclic.
        :returns [(int, int)]:  A list of merge points (address and number of times looped).
        """

        graph = networkx.DiGraph(cfg.graph)
        reversed_cyclic_graph = shallow_reverse(graph_with_loops)

        # Remove all "FakeRet" edges
        fakeret_edges = [
            (src, dst) for src, dst, data in graph.edges(data=True)
            if data['jumpkind'] in ('Ijk_FakeRet', 'Ijk_Exit')
        ]
        graph.remove_edges_from(fakeret_edges)

        # Remove all "FakeRet" edges from cyclic_graph as well
        fakeret_edges = [
            (src, dst) for src, dst, data in reversed_cyclic_graph.edges(data=True)
            if data['jumpkind'] in ('Ijk_FakeRet', 'Ijk_Exit')
        ]
        reversed_cyclic_graph.remove_edges_from(fakeret_edges)

        # Perform a topological sort
        sorted_nodes = networkx.topological_sort(graph)

        nodes = [ n for n in sorted_nodes if graph.in_degree(n) > 1 and n.looping_times == 0 ]

        # Reorder nodes based on post-dominance relations
        nodes = sorted(nodes, key=cmp_to_key(lambda n1, n2: (
            1 if self._post_dominate(reversed_cyclic_graph, n1, n2)
            else (-1 if self._post_dominate(reversed_cyclic_graph, n2, n1) else 0)
        )))

        return [ (n.addr, n.looping_times) for n in nodes ] 
Example #24
Source File: xcodeproj_file.py    From GYP3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def SortGroups(self):
    # Sort the children of the mainGroup (like "Source" and "Products")
    # according to their defined order.
    self._properties['mainGroup']._properties['children'].sort(key=cmp_to_key(XCHierarchicalElement.CompareRootGroup))

    # Sort everything else by putting group before files, and going
    # alphabetically by name within sections of groups and files.  SortGroup
    # is recursive.
    for group in self._properties['mainGroup']._properties['children']:
      if not isinstance(group, PBXGroup):
        continue

      if group.Name() == 'Products':
        # The Products group is a special case.  Instead of sorting
        # alphabetically, sort things in the order of the targets that
        # produce the products.  To do this, just build up a new list of
        # products based on the targets.
        products = []
        for target in self._properties['targets']:
          if not isinstance(target, PBXNativeTarget):
            continue
          product = target._properties['productReference']
          # Make sure that the product is already in the products group.
          assert product in group._properties['children']
          products.append(product)

        # Make sure that this process doesn't miss anything that was already
        # in the products group.
        assert len(products) == len(group._properties['children'])
        group._properties['children'] = products
      else:
        group.SortGroup() 
Example #25
Source File: loaders.py    From spidermon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_testcase_names(self, monitor_class):
        def is_test_method(
            attrname, class_name=monitor_class, prefix=self.testMethodPrefix
        ):
            return attrname.startswith(prefix) and hasattr(
                getattr(class_name, attrname), "__call__"
            )

        test_function_names = list(filter(is_test_method, dir(monitor_class)))
        if self.sortTestMethodsUsing:
            test_function_names.sort(key=_cmp_to_key(self.sortTestMethodsUsing))
        return test_function_names

    # TODO: hide methods? 
Example #26
Source File: test_functools.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_hash(self):
        def mycmp(x, y):
            return y - x
        key = functools.cmp_to_key(mycmp)
        k = key(10)
        self.assertRaises(TypeError, hash(k)) 
Example #27
Source File: test_functools.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_cmp_to_key(self):
        def mycmp(x, y):
            return y - x
        self.assertEqual(sorted(range(5), key=functools.cmp_to_key(mycmp)),
                         [4, 3, 2, 1, 0]) 
Example #28
Source File: pstats.py    From oss-ftp with MIT License 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self 
Example #29
Source File: loader.py    From oss-ftp with MIT License 5 votes vote down vote up
def getTestCaseNames(self, testCaseClass):
        """Return a sorted sequence of method names found within testCaseClass
        """
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
        testFnNames = filter(isTestMethod, dir(testCaseClass))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
        return testFnNames 
Example #30
Source File: pstats.py    From Computable with MIT License 5 votes vote down vote up
def sort_stats(self, *field):
        if not field:
            self.fcn_list = 0
            return self
        if len(field) == 1 and isinstance(field[0], (int, long)):
            # Be compatible with old profiler
            field = [ {-1: "stdname",
                       0:  "calls",
                       1:  "time",
                       2:  "cumulative"}[field[0]] ]

        sort_arg_defs = self.get_sort_arg_defs()
        sort_tuple = ()
        self.sort_type = ""
        connector = ""
        for word in field:
            sort_tuple = sort_tuple + sort_arg_defs[word][0]
            self.sort_type += connector + sort_arg_defs[word][1]
            connector = ", "

        stats_list = []
        for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
            stats_list.append((cc, nc, tt, ct) + func +
                              (func_std_string(func), func))

        stats_list.sort(key=cmp_to_key(TupleComp(sort_tuple).compare))

        self.fcn_list = fcn_list = []
        for tuple in stats_list:
            fcn_list.append(tuple[-1])
        return self