Python distutils.version.LooseVersion() Examples

The following are 30 code examples of distutils.version.LooseVersion(). 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 distutils.version , or try the search function .
Example #1
Source File: utils.py    From dataiku-contrib with Apache License 2.0 7 votes vote down vote up
def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True,
           preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):
    """A wrapper for Scikit-Image resize().
    Scikit-Image generates warnings on every call to resize() if it doesn't
    receive the right parameters. The right parameters depend on the version
    of skimage. This solves the problem by using different parameters per
    version. And it provides a central place to control resizing defaults.
    """
    if LooseVersion(skimage.__version__) >= LooseVersion("0.14"):
        # New in 0.14: anti_aliasing. Default it to False for backward
        # compatibility with skimage 0.13.
        return skimage.transform.resize(
            image, output_shape,
            order=order, mode=mode, cval=cval, clip=clip,
            preserve_range=preserve_range, anti_aliasing=anti_aliasing,
            anti_aliasing_sigma=anti_aliasing_sigma)
    else:
        return skimage.transform.resize(
            image, output_shape,
            order=order, mode=mode, cval=cval, clip=clip,
            preserve_range=preserve_range) 
Example #2
Source File: connection_manager.py    From plugin.video.emby with GNU General Public License v3.0 7 votes vote down vote up
def _compare_versions(self, a, b):

        ''' -1 a is smaller
            1 a is larger
            0 equal
        '''
        a = LooseVersion(a)
        b = LooseVersion(b)

        if a < b:
            return -1

        if a > b:
            return 1
        
        return 0 
Example #3
Source File: bootstrap.py    From loaner with Apache License 2.0 7 votes vote down vote up
def _is_latest_version():
  """Checks if the app is up to date and sets bootstrap to incomplete if not.

  Checks whether the running version is the same as the deployed version as an
  app that is not updated should trigger bootstrap moving back to an incomplete
  state, thus signaling that certain tasks need to be run again.

  Returns:
    True if running matches deployed version and not a new install, else False.
  """
  if _is_new_deployment():
    return False

  up_to_date = version.LooseVersion(
      constants.APP_VERSION) == version.LooseVersion(
          config_model.Config.get('running_version'))

  if not up_to_date and not is_bootstrap_started():
    # Set the updates tasks to incomplete so that they run again.
    config_model.Config.set('bootstrap_completed', False)
    for task in _BOOTSTRAP_UPDATE_TASKS:
      status_entity = bootstrap_status_model.BootstrapStatus.get_or_insert(task)
      status_entity.success = False
      status_entity.put()
  return up_to_date 
Example #4
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 7 votes vote down vote up
def compare_version(a, b):

    ''' -1 a is smaller
        1 a is larger
        0 equal
    '''
    a = LooseVersion(a)
    b = LooseVersion(b)

    if a < b:
        return -1

    if a > b:
        return 1

    return 0 
Example #5
Source File: generate_legacy_storage_files.py    From recruit with Apache License 2.0 6 votes vote down vote up
def create_msgpack_data():
    data = create_data()
    if _loose_version < LooseVersion('0.17.0'):
        del data['frame']['mixed_dup']
        del data['panel']['mixed_dup']
        del data['frame']['dup']
        del data['panel']['dup']
    if _loose_version < LooseVersion('0.18.0'):
        del data['series']['dt_tz']
        del data['frame']['dt_mixed_tzs']
    # Not supported
    del data['sp_series']
    del data['sp_frame']
    del data['series']['cat']
    del data['series']['period']
    del data['frame']['cat_onecol']
    del data['frame']['cat_and_float']
    del data['scalars']['period']
    if _loose_version < LooseVersion('0.23.0'):
        del data['index']['interval']
    del data['offsets']
    return _u(data) 
Example #6
Source File: jmxutils.py    From cassandra-dtest with Apache License 2.0 6 votes vote down vote up
def remove_perf_disable_shared_mem(node):
    """
    The Jolokia agent is incompatible with the -XX:+PerfDisableSharedMem JVM
    option (see https://github.com/rhuss/jolokia/issues/198 for details).  This
    edits cassandra-env.sh (or the Windows equivalent), or jvm.options file on 3.2+ to remove that option.
    """
    if node.get_cassandra_version() >= LooseVersion('3.2'):
        pattern = r'\-XX:\+PerfDisableSharedMem'
        replacement = '#-XX:+PerfDisableSharedMem'
        for f in glob.glob(os.path.join(node.get_conf_dir(), common.JVM_OPTS_PATTERN)):
            if os.path.isfile(f):
                common.replace_in_file(f, pattern, replacement)
    else:
        conf_file = node.envfilename()
        pattern = 'PerfDisableSharedMem'
        replacement = ''
        common.replace_in_file(conf_file, pattern, replacement) 
Example #7
Source File: gmacpyutil.py    From macops with Apache License 2.0 6 votes vote down vote up
def GetTrack():
  """Retrieve the currently set track.

  Returns:
    track: As defined in Track key, stable if undefined, or unstable
        if Major OS version does not match currently supported version.
  """
  major_os_version = GetMajorOSVersion()
  if not major_os_version:
    track = 'stable'
  else:
    track = MachineInfoForKey('Track')
    if distutils_version.LooseVersion(
        major_os_version) > distutils_version.LooseVersion(MAX_SUPPORTED_VERS):
      track = 'unstable'
    elif track not in ['stable', 'testing', 'unstable']:
      track = 'stable'
  return track 
Example #8
Source File: test_pickle_store.py    From arctic with GNU Lesser General Public License v2.1 6 votes vote down vote up
def test_read_backward_compatibility():
    """Test backwards compatibility with a pickled file that's created with Python 2.7.3,
    Numpy 1.7.1_ahl2 and Pandas 0.14.1
    """
    fname = path.join(path.dirname(__file__), "data", "test-data.pkl")

    # For newer versions; verify that unpickling fails when using cPickle
    if PANDAS_VERSION >= LooseVersion("0.16.1"):
        if sys.version_info[0] >= 3:
            with pytest.raises(UnicodeDecodeError), open(fname) as fh:
                cPickle.load(fh)
        else:
            with pytest.raises(TypeError), open(fname) as fh:
                cPickle.load(fh)

    # Verify that PickleStore() uses a backwards compatible unpickler.
    store = PickleStore()

    with open(fname) as fh:
        # PickleStore compresses data with lz4
        version = {'blob': compressHC(fh.read())}
    df = store.read(sentinel.arctic_lib, version, sentinel.symbol)

    expected = pd.DataFrame(range(4), pd.date_range(start="20150101", periods=4))
    assert (df == expected).all().all() 
Example #9
Source File: main.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def get_api_obj(cls):
        """returns object to call ahv provider specific apis"""

        client = get_api_client()
        calm_version = Version.get_version("Calm")
        api_handlers = AhvBase.api_handlers

        # Return min version that is greater or equal to user calm version
        supported_versions = []
        for k in api_handlers.keys():
            if LV(k) <= LV(calm_version):
                supported_versions.append(k)

        latest_version = max(supported_versions, key=lambda x: LV(x))
        api_handler = api_handlers[latest_version]
        return api_handler(client.connection) 
Example #10
Source File: _core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _plot(cls, ax, y, style=None, bw_method=None, ind=None,
              column_num=None, stacking_id=None, **kwds):
        from scipy.stats import gaussian_kde
        from scipy import __version__ as spv

        y = remove_na_arraylike(y)

        if LooseVersion(spv) >= '0.11.0':
            gkde = gaussian_kde(y, bw_method=bw_method)
        else:
            gkde = gaussian_kde(y)
            if bw_method is not None:
                msg = ('bw_method was added in Scipy 0.11.0.' +
                       ' Scipy version in use is {spv}.'.format(spv=spv))
                warnings.warn(msg)

        y = gkde.evaluate(ind)
        lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
        return lines 
Example #11
Source File: pytables.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _tables():
    global _table_mod
    global _table_file_open_policy_is_strict
    if _table_mod is None:
        import tables
        _table_mod = tables

        # version requirements
        if LooseVersion(tables.__version__) < LooseVersion('3.0.0'):
            raise ImportError("PyTables version >= 3.0.0 is required")

        # set the file open policy
        # return the file open policy; this changes as of pytables 3.1
        # depending on the HDF5 version
        try:
            _table_file_open_policy_is_strict = (
                tables.file._FILE_OPEN_POLICY == 'strict')
        except AttributeError:
            pass

    return _table_mod

# interface to/from ### 
Example #12
Source File: test_offsets.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_fallback_plural(self):
        # test moving from daylight savings to standard time
        import dateutil
        for tz, utc_offsets in self.timezone_utc_offsets.items():
            hrs_pre = utc_offsets['utc_offset_daylight']
            hrs_post = utc_offsets['utc_offset_standard']

            if LooseVersion(dateutil.__version__) < LooseVersion('2.6.0'):
                # buggy ambiguous behavior in 2.6.0
                # GH 14621
                # https://github.com/dateutil/dateutil/issues/321
                self._test_all_offsets(
                    n=3, tstart=self._make_timestamp(self.ts_pre_fallback,
                                                     hrs_pre, tz),
                    expected_utc_offset=hrs_post)
            elif LooseVersion(dateutil.__version__) > LooseVersion('2.6.0'):
                # fixed, but skip the test
                continue 
Example #13
Source File: parquet.py    From recruit with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # since pandas is a dependency of pyarrow
        # we need to import on first use
        try:
            import pyarrow
            import pyarrow.parquet
        except ImportError:
            raise ImportError(
                "pyarrow is required for parquet support\n\n"
                "you can install via conda\n"
                "conda install pyarrow -c conda-forge\n"
                "\nor via pip\n"
                "pip install -U pyarrow\n"
            )
        if LooseVersion(pyarrow.__version__) < '0.9.0':
            raise ImportError(
                "pyarrow >= 0.9.0 is required for parquet support\n\n"
                "you can install via conda\n"
                "conda install pyarrow -c conda-forge\n"
                "\nor via pip\n"
                "pip install -U pyarrow\n"
            )

        self.api = pyarrow 
Example #14
Source File: test_compat.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_invalid_numexpr_version(engine, parser):
    def testit():
        a, b = 1, 2  # noqa
        res = pd.eval('a + b', engine=engine, parser=parser)
        assert res == 3

    if engine == 'numexpr':
        try:
            import numexpr as ne
        except ImportError:
            pytest.skip("no numexpr")
        else:
            if (LooseVersion(ne.__version__) <
                    LooseVersion(_MIN_NUMEXPR_VERSION)):
                with pytest.raises(ImportError):
                    testit()
            else:
                testit()
    else:
        testit() 
Example #15
Source File: test_rank.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_rank_methods_series(self):
        pytest.importorskip('scipy.stats.special')
        rankdata = pytest.importorskip('scipy.stats.rankdata')
        import scipy

        xs = np.random.randn(9)
        xs = np.concatenate([xs[i:] for i in range(0, 9, 2)])  # add duplicates
        np.random.shuffle(xs)

        index = [chr(ord('a') + i) for i in range(len(xs))]

        for vals in [xs, xs + 1e6, xs * 1e-6]:
            ts = Series(vals, index=index)

            for m in ['average', 'min', 'max', 'first', 'dense']:
                result = ts.rank(method=m)
                sprank = rankdata(vals, m if m != 'first' else 'ordinal')
                expected = Series(sprank, index=index)

                if LooseVersion(scipy.__version__) >= LooseVersion('0.17.0'):
                    expected = expected.astype('float64')
                tm.assert_series_equal(result, expected) 
Example #16
Source File: feather_format.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _try_import():
    # since pandas is a dependency of pyarrow
    # we need to import on first use
    try:
        import pyarrow
        from pyarrow import feather
    except ImportError:
        # give a nice error message
        raise ImportError("pyarrow is not installed\n\n"
                          "you can install via conda\n"
                          "conda install pyarrow -c conda-forge\n"
                          "or via pip\n"
                          "pip install -U pyarrow\n")

    if LooseVersion(pyarrow.__version__) < LooseVersion('0.9.0'):
        raise ImportError("pyarrow >= 0.9.0 required for feather support\n\n"
                          "you can install via conda\n"
                          "conda install pyarrow -c conda-forge"
                          "or via pip\n"
                          "pip install -U pyarrow\n")

    return feather, pyarrow 
Example #17
Source File: test_rank.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_rank_methods_frame(self):
        pytest.importorskip('scipy.stats.special')
        rankdata = pytest.importorskip('scipy.stats.rankdata')
        import scipy

        xs = np.random.randint(0, 21, (100, 26))
        xs = (xs - 10.0) / 10.0
        cols = [chr(ord('z') - i) for i in range(xs.shape[1])]

        for vals in [xs, xs + 1e6, xs * 1e-6]:
            df = DataFrame(vals, columns=cols)

            for ax in [0, 1]:
                for m in ['average', 'min', 'max', 'first', 'dense']:
                    result = df.rank(axis=ax, method=m)
                    sprank = np.apply_along_axis(
                        rankdata, ax, vals,
                        m if m != 'first' else 'ordinal')
                    sprank = sprank.astype(np.float64)
                    expected = DataFrame(sprank, columns=cols)

                    if (LooseVersion(scipy.__version__) >=
                            LooseVersion('0.17.0')):
                        expected = expected.astype('float64')
                    tm.assert_frame_equal(result, expected) 
Example #18
Source File: test_cqlsh.py    From cassandra-dtest with Apache License 2.0 6 votes vote down vote up
def test_past_and_future_dates(self):
        self.cluster.populate(1)
        self.cluster.start(wait_for_binary_proto=True)

        node1, = self.cluster.nodelist()

        node1.run_cqlsh(cmds="""
            CREATE KEYSPACE simple WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
            use simple;
            create TABLE simpledate (id int PRIMARY KEY , value timestamp ) ;
            insert into simpledate (id, value) VALUES (1, '2143-04-19 11:21:01+0000');
            insert into simpledate (id, value) VALUES (2, '1943-04-19 11:21:01+0000')""")

        session = self.patient_cql_connection(node1)
        list(session.execute("select id, value from simple.simpledate"))

        output, err = self.run_cqlsh(node1, 'use simple; SELECT * FROM simpledate')

        if self.cluster.version() >= LooseVersion('3.4'):
            assert "2143-04-19 11:21:01.000000+0000" in output
            assert "1943-04-19 11:21:01.000000+0000" in output
        else:
            assert "2143-04-19 11:21:01+0000" in output
            assert "1943-04-19 11:21:01+0000" in output 
Example #19
Source File: test_packers.py    From recruit with Apache License 2.0 5 votes vote down vote up
def compare_series_dt_tz(self, result, expected, typ, version):
        # 8260
        # dtype is object < 0.17.0
        if LooseVersion(version) < LooseVersion('0.17.0'):
            expected = expected.astype(object)
            tm.assert_series_equal(result, expected)
        else:
            tm.assert_series_equal(result, expected) 
Example #20
Source File: test_packers.py    From recruit with Apache License 2.0 5 votes vote down vote up
def compare(self, current_data, all_data, vf, version):
        # GH12277 encoding default used to be latin-1, now utf-8
        if LooseVersion(version) < LooseVersion('0.18.0'):
            data = read_msgpack(vf, encoding='latin-1')
        else:
            data = read_msgpack(vf)
        self.check_min_structure(data, version)
        for typ, dv in data.items():
            assert typ in all_data, ('unpacked data contains '
                                     'extra key "{0}"'
                                     .format(typ))
            for dt, result in dv.items():
                assert dt in current_data[typ], ('data["{0}"] contains extra '
                                                 'key "{1}"'.format(typ, dt))
                try:
                    expected = current_data[typ][dt]
                except KeyError:
                    continue

                # use a specific comparator
                # if available
                comp_method = "compare_{typ}_{dt}".format(typ=typ, dt=dt)
                comparator = getattr(self, comp_method, None)
                if comparator is not None:
                    comparator(result, expected, typ, version)
                else:
                    check_arbitrary(result, expected)

        return data 
Example #21
Source File: auth_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def assert_unauthenticated(self, user, password):
        with pytest.raises(NoHostAvailable) as response:
            node = self.cluster.nodelist()[0]
            self.cql_connection(node, user=user, password=password)
        host, error = response._excinfo[1].errors.popitem()

        message = "Provided username {user} and/or password are incorrect".format(user=user)\
            if node.cluster.version() >= LooseVersion('3.10') \
            else "Username and/or password are incorrect"
        pattern = 'Failed to authenticate to {host}: Error from server: code=0100 ' \
                  '[Bad credentials] message="{message}"'.format(host=host, message=message)

        assert isinstance(error, AuthenticationFailed), "Expected AuthenticationFailed, got {error}".format(error=error)
        assert pattern in repr(error) 
Example #22
Source File: test_parquet.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_categorical(self, fp):
        if LooseVersion(fastparquet.__version__) < LooseVersion("0.1.3"):
            pytest.skip("CategoricalDtype not supported for older fp")
        df = pd.DataFrame({'a': pd.Categorical(list('abc'))})
        check_round_trip(df, fp) 
Example #23
Source File: test_parquet.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_basic(self, fp, df_full):
        df = df_full

        # additional supported types for fastparquet
        if LooseVersion(fastparquet.__version__) >= LooseVersion('0.1.4'):
            df['datetime_tz'] = pd.date_range('20130101', periods=3,
                                              tz='US/Eastern')
        df['timedelta'] = pd.timedelta_range('1 day', periods=3)
        check_round_trip(df, fp) 
Example #24
Source File: test_pickle.py    From recruit with Apache License 2.0 5 votes vote down vote up
def compare_sp_frame_float(result, expected, typ, version):
    if LooseVersion(version) <= LooseVersion('0.18.1'):
        tm.assert_sp_frame_equal(result, expected, exact_indices=False,
                                 check_dtype=False)
    else:
        tm.assert_sp_frame_equal(result, expected) 
Example #25
Source File: test_pickle.py    From recruit with Apache License 2.0 5 votes vote down vote up
def compare_sp_series_ts(res, exp, typ, version):
    # SparseTimeSeries integrated into SparseSeries in 0.12.0
    # and deprecated in 0.17.0
    if version and LooseVersion(version) <= LooseVersion("0.12.0"):
        tm.assert_sp_series_equal(res, exp, check_series_type=False)
    else:
        tm.assert_sp_series_equal(res, exp) 
Example #26
Source File: _test_decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def safe_import(mod_name, min_version=None):
    """
    Parameters:
    -----------
    mod_name : str
        Name of the module to be imported
    min_version : str, default None
        Minimum required version of the specified mod_name

    Returns:
    --------
    object
        The imported module if successful, or False
    """
    try:
        mod = __import__(mod_name)
    except ImportError:
        return False

    if not min_version:
        return mod
    else:
        import sys
        try:
            version = getattr(sys.modules[mod_name], '__version__')
        except AttributeError:
            # xlrd uses a capitalized attribute name
            version = getattr(sys.modules[mod_name], '__VERSION__')
        if version:
            from distutils.version import LooseVersion
            if LooseVersion(version) >= LooseVersion(min_version):
                return mod

    return False 
Example #27
Source File: _test_decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _skip_if_mpl_2_2():
    mod = safe_import("matplotlib")

    if mod:
        v = mod.__version__
        if LooseVersion(v) > LooseVersion('2.1.2'):
            return True
        else:
            mod.use("Agg", warn=False) 
Example #28
Source File: ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def __init__(self, name):
        from pandas.core.computation.check import (_NUMEXPR_INSTALLED,
                                                   _NUMEXPR_VERSION)
        if name not in _mathops or (
                _NUMEXPR_INSTALLED and
                _NUMEXPR_VERSION < LooseVersion('2.6.9') and
                name in ('floor', 'ceil')
        ):
            raise ValueError(
                "\"{0}\" is not a supported function".format(name))

        self.name = name
        self.func = getattr(np, name) 
Example #29
Source File: user_functions_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def test_udf_with_udt(self):
        """
        Test UDFs that operate on non-frozen UDTs.
        @jira_ticket CASSANDRA-7423
        @since 3.6
        """
        session = self.prepare()
        session.execute("create type test (a text, b int);")
        session.execute("create function funk(udt test) called on null input returns int language java as 'return Integer.valueOf(udt.getInt(\"b\"));';")

        if self.cluster.version() >= LooseVersion('3.6'):
            frozen_vals = (False, True)
        else:
            frozen_vals = (True,)

        for frozen in frozen_vals:
            logger.debug("Using {} UDTs".format("frozen" if frozen else "non-frozen"))

            table_name = "tab_frozen" if frozen else "tab"
            column_type = "frozen<test>" if frozen else "test"
            session.execute("create table {} (key int primary key, udt {});".format(table_name, column_type))

            session.execute("insert into %s (key, udt) values (1, {a: 'un', b:1});" % (table_name,))
            session.execute("insert into %s (key, udt) values (2, {a: 'deux', b:2});" % (table_name,))
            session.execute("insert into %s (key, udt) values (3, {a: 'trois', b:3});" % (table_name,))

            assert_one(session, "select sum(funk(udt)) from {}".format(table_name), [6])

            assert_invalid(session, "drop type test;") 
Example #30
Source File: test_cqlsh.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def test_pycodestyle_compliance(self):
        """
        @jira_ticket CASSANDRA-10066
        Checks that cqlsh is compliant with pycodestyle (formally known as pep8) with the following command:
        pycodestyle --ignore E501,E402,E731,W503 pylib/cqlshlib/*.py bin/cqlsh.py
        """
        cluster = self.cluster

        if cluster.version() < LooseVersion('2.2'):
            cqlsh_path = os.path.join(cluster.get_install_dir(), 'bin', 'cqlsh')
        else:
            cqlsh_path = os.path.join(cluster.get_install_dir(), 'bin', 'cqlsh.py')

        cqlshlib_path = os.path.join(cluster.get_install_dir(), 'pylib', 'cqlshlib')
        cqlshlib_paths = os.listdir(cqlshlib_path)
        cqlshlib_paths = [os.path.join(cqlshlib_path, x) for x in cqlshlib_paths if '.py' in x and '.pyc' not in x]

        cmds = ['pycodestyle', '--ignore', 'E501,E402,E731,W503', cqlsh_path] + cqlshlib_paths

        logger.debug(cmds)

        p = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()

        assert 0 == len(stdout), stdout
        assert 0 == len(stderr), stderr