예제 #1
0
    def one_wire_version(self, data):
        self.sm.data_ready.disconnect()

        self.watchdog_pbar.setRange(0, 1)
        self.watchdog_pbar.setValue(1)
        self.watchdog_pbar_lbl.setText("Complete")
        
        pattern = r"([0-9]+\.[0-9]+[a-z])"

        if re.search(pattern, data):
            one_wire_ver = re.search(pattern, data).group()
        else:
            one_wire_ver = None

        if (LegacyVersion(self.one_wire_file_version) > LegacyVersion(one_wire_ver)
            or not one_wire_ver):
            self.one_wire_pbar_lbl.setText("Erasing flash. . .")
            self.sm.data_ready.connect(self.send_hex_file)
            self.reprogram_one_wire.emit()
        else:
            QMessageBox.warning(self, "Warning!", "File version is not newer "
                                "than board version; skipping...")
            self.report.write_data("one_wire_ver", one_wire_ver, "PASS")
            self.tu.one_wire_prog_status.setText("1-Wire Programming: PASS")
            self.tu.one_wire_prog_status.setStyleSheet(
                self.threadlink.status_style_pass)
            self.one_wire_pbar_lbl.setText("Complete.")
            self.one_wire_pbar.setRange(0, 1)
            self.one_wire_pbar.setValue(1)
            self.is_complete = True
            self.complete_signal.emit()
예제 #2
0
def msvc14_gen_lib_options(*args, **kwargs):
    """
    Patched "distutils._msvccompiler.gen_lib_options" for fix
    compatibility between "numpy.distutils" and "distutils._msvccompiler"
    (for Numpy < 1.11.2)
    """
    if "numpy.distutils" in sys.modules:
        import numpy as np
        if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
            return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
    return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)
예제 #3
0
    def test_specifiers(self, version, spec, expected):
        spec = LegacySpecifier(spec, prereleases=True)

        if expected:
            # Test that the plain string form works
            assert spec.contains(version)

            # Test that the version instance form works
            assert spec.contains(LegacyVersion(version))
        else:
            # Test that the plain string form works
            assert not spec.contains(version)

            # Test that the version instance form works
            assert not spec.contains(LegacyVersion(version))
예제 #4
0
def sort_cpe_matches(cpe_matches: list, requested_version: str) -> namedtuple:
    if requested_version.isdigit() or is_valid_dotted_version(
            requested_version):
        version_numbers = get_version_numbers(target_values=cpe_matches)
        if requested_version in version_numbers:
            return [
                product for product in cpe_matches
                if product.version_number == requested_version
            ][0]
        else:
            version_numbers.append(requested_version)
            version_numbers.sort(key=lambda v: LegacyVersion(parse(v)))
            closest_match = get_closest_matches(
                target_values=version_numbers,
                search_word=requested_version)[0]
            return [
                product for product in cpe_matches
                if product.version_number == closest_match
            ][0]
    else:
        warn(
            'Warning: Version returned from CPE match has invalid type. Returned CPE might not contain relevant version number'
        )

        return cpe_matches[0]
예제 #5
0
def splitcondaname(cname):
    xx = cname.split('-')
    variant = xx.pop().split('.')[0]
    ver = xx.pop()
    base = '-'.join(xx)
    try:
        pver = Version(ver)
    except InvalidVersion:
        tver = LegacyVersion(ver)
        pp = []
        for v in tver._key[1]:
            try:
                pp.append(str(int(v)))
            except ValueError:
                break
        pver = Version('.'.join(pp)) if pp else tver
        print("WARNING: Pack {} LegacyVersion {} resolved as {}".format(
            cname, ver, pver))
    except Exception:
        print("FAILED version parsing!")
        raise
    if re.match('py\d\d\.*', variant):
        pyver = variant[:4]
        hashvar = variant[4:]
    else:
        pyver = None
        hashvar = variant
    return base, pver, pyver, hashvar
예제 #6
0
파일: version.py 프로젝트: zakibelm/AnyBlok
    def parse_other(self, other):
        if other is None:
            other = LegacyVersion('')
        elif not isinstance(other, (Version, LegacyVersion)):
            other = parse_version(other)

        return other
예제 #7
0
    def compare_version(self, version: str):
        """Compare main app file version and board version using 
        packaging.version LegacyVersion and flash the board with the file if
        the file version is higher than the board version."""
        if LegacyVersion(self.main_app_file_version) > LegacyVersion(version):
            self.start_flash()
        else:
            QMessageBox.warning(self, "Warning!", "File version is not newer "
                                "than board version; skipping...")
            self.tu.xmega_prog_status.setStyleSheet(
                self.threadlink.status_style_pass)
            self.tu.xmega_prog_status.setText("XMega Programming: PASS")

            self.batch_pbar_lbl.setText("Complete.")
            self.batch_pbar.setRange(0, 1)
            self.batch_pbar.setValue(1)
            self.start_watchdog_reset()
예제 #8
0
파일: version.py 프로젝트: vinifmor/bauh
def normalize_version(version: str) -> LegacyVersion:
    final_version = version.strip()

    if not RE_VERSION_WITH_EPOCH.match(final_version):
        final_version = f'0:{final_version}'

    if not RE_VERSION_WITH_RELEASE.match(final_version):
        final_version = f'{final_version}-1'

    return LegacyVersion(final_version)
예제 #9
0
    def get_history(self, pkg: AppImage) -> PackageHistory:
        history = []
        res = PackageHistory(pkg, history, -1)

        app_con = self._get_db_connection(DATABASE_APPS_FILE)

        if not app_con:
            return res

        try:
            cursor = app_con.cursor()

            cursor.execute(query.FIND_APP_ID_BY_NAME_AND_GITHUB.format(pkg.name.lower(), pkg.github.lower() if pkg.github else ''))
            app_tuple = cursor.fetchone()

            if not app_tuple:
                self.logger.warning(f"Could not retrieve {pkg} from the database '{DATABASE_APPS_FILE}'")
                return res
        except:
            self.logger.error(f"An exception happened while querying the database file '{DATABASE_APPS_FILE}'")
            traceback.print_exc()
            app_con.close()
            return res

        app_con.close()

        releases_con = self._get_db_connection(DATABASE_RELEASES_FILE)

        if not releases_con:
            return res

        try:
            cursor = releases_con.cursor()

            releases = cursor.execute(query.FIND_RELEASES_BY_APP_ID.format(app_tuple[0]))

            if releases:
                treated_releases = [(LegacyVersion(r[0]), *r[1:]) for r in releases]
                treated_releases.sort(key=self._sort_release, reverse=True)

                for idx, tup in enumerate(treated_releases):
                    ver = str(tup[0])
                    history.append({'0_version': ver,
                                    '1_published_at': datetime.strptime(tup[2], '%Y-%m-%dT%H:%M:%SZ') if tup[
                                        2] else '', '2_url_download': tup[1]})

                    if res.pkg_status_idx == -1 and pkg.version == ver:
                        res.pkg_status_idx = idx

                return res
        except:
            self.logger.error(f"An exception happened while querying the database file '{DATABASE_RELEASES_FILE}'")
            traceback.print_exc()
        finally:
            releases_con.close()
예제 #10
0
    def get_latest_version(filenames: list) -> (str, str):
        current_version = None
        current_filename = None

        for name in filenames:
            p = r"([0-9]+\.[0-9]+[a-z])"
            try:
                version = re.search(p, str(name)).group()
            except AttributeError:
                continue

            if not current_version:
                current_version = version
                current_filename = name

            if LegacyVersion(version) > LegacyVersion(current_version):
                current_version = version
                current_filename = name

        return (current_filename, current_version)
예제 #11
0
def cython_chk(VERSION, verbose=True):
    from mpidistutils import log
    if verbose:
        warn = lambda msg='': sys.stderr.write(msg+'\n')
    else:
        warn = lambda msg='': None
    #
    try:
        import Cython
    except ImportError:
        warn("*"*80)
        warn()
        warn(" You need Cython to generate C source files.\n")
        warn("   $ python -m pip install cython")
        warn()
        warn("*"*80)
        return False
    #
    REQUIRED = VERSION
    CYTHON_VERSION = Cython.__version__
    if VERSION is not None:
        m = re.match(r"(\d+\.\d+(?:\.\d+)?).*", CYTHON_VERSION)
        if m:
            REQUIRED  = Version(VERSION)
            AVAILABLE = Version(m.groups()[0])
        else:
            REQUIRED  = LegacyVersion(VERSION)
            AVAILABLE = LegacyVersion(CYTHON_VERSION)
        if AVAILABLE < REQUIRED:
            warn("*"*80)
            warn()
            warn(" You need Cython >= {0} (you have version {1}).\n"
                 .format(REQUIRED, CYTHON_VERSION))
            warn("   $ python -m pip install --upgrade cython")
            warn()
            warn("*"*80)
            return False
    #
    if verbose:
        log.info("using Cython version %s" % CYTHON_VERSION)
    return True
예제 #12
0
def version(env=os.environ):
    with open(os.devnull, 'wb') as devnull:
        try:
            ninja = which(env.get('NINJA', ['ninja', 'ninja-build']), env)
            output = subprocess.check_output('{} --version'.format(ninja),
                                             shell=True,
                                             universal_newlines=True,
                                             stderr=devnull)
            return LegacyVersion(output.strip())
        except IOError:
            pass
    return None
예제 #13
0
    def test_nucleus_sampling(self):
        vocab = text_utils.VocabFromText(self.VOCAB_EXAMPLE_SENTENCES)

        model_config = self.config.model_config.butd
        model = TestDecoderModel(model_config, vocab)
        model.build()
        model.eval()

        sample = Sample()
        sample.dataset_name = "coco"
        sample.dataset_type = "test"
        sample.image_feature_0 = torch.randn(100, 2048)
        sample.answers = torch.zeros((5, 10), dtype=torch.long)
        sample_list = SampleList([sample])

        tokens = model(sample_list)["captions"]

        # these are expected tokens for sum_threshold = 0.5

        # Because of a bug fix in https://github.com/pytorch/pytorch/pull/47386
        # the torch.Tensor.multinomail will generate different random sequence.
        # TODO: Remove this hack after OSS uses later version of PyTorch.
        if LegacyVersion(torch.__version__) > LegacyVersion("1.7.1"):
            expected_tokens = [1.0, 23.0, 38.0, 30.0, 5.0, 11.0, 2.0]
        else:
            expected_tokens = [
                1.0,
                29.0,
                11.0,
                11.0,
                39.0,
                10.0,
                31.0,
                4.0,
                19.0,
                39.0,
                2.0,
            ]

        self.assertEqual(tokens[0].tolist(), expected_tokens)
예제 #14
0
def find_matching_cpe_product(cpe_matches: List[Product], requested_version: str) -> Product:
    if requested_version.isdigit() or is_valid_dotted_version(requested_version):
        version_numbers = [t.version_number for t in cpe_matches]
        if requested_version in version_numbers:
            return find_cpe_product_with_version(cpe_matches, requested_version)
        version_numbers.append(requested_version)
        version_numbers.sort(key=lambda v: LegacyVersion(parse(v)))
        next_closest_version = find_next_closest_version(version_numbers, requested_version)
        return find_cpe_product_with_version(cpe_matches, next_closest_version)
    if requested_version == 'ANY':
        return find_cpe_product_with_version(cpe_matches, 'ANY')
    logging.warning('Version returned from CPE match has invalid type. Returned CPE might not contain relevant version number')
    return cpe_matches[0]
예제 #15
0
def version(env=os.environ):
    with open(os.devnull, 'wb') as devnull:
        try:
            make = which(env.get('MAKE', ['make', 'gmake']), env)
            output = subprocess.check_output('{} --version'.format(make),
                                             shell=True,
                                             universal_newlines=True,
                                             stderr=devnull)
            m = re.match(r'GNU Make ([\d\.]+)', output)
            if m:
                return LegacyVersion(m.group(1))
        except IOError:
            pass
    return None
예제 #16
0
def version(env=os.environ):
    with open(os.devnull, 'wb') as devnull:
        try:
            msbuild = which(env.get('MSBUILD', ['msbuild', 'xbuild']), env)
            output = subprocess.check_output(
                '{} /version'.format(msbuild),
                shell=True, universal_newlines=True, stderr=devnull
            )
            m = re.search(r'([\d\.]+)$', output)
            if m:
                return LegacyVersion(m.group(1))
        except IOError:
            pass
    return None
예제 #17
0
파일: version.py 프로젝트: vinifmor/bauh
def match_required_version(current_version: str, operator: str,
                           required_version: str) -> bool:
    final_required, final_current = required_version.strip(
    ), current_version.strip()

    required_has_epoch = bool(RE_VERSION_WITH_EPOCH.match(final_required))
    current_no_epoch = RE_VERSION_WITH_EPOCH.split(final_current)
    current_has_epoch = len(current_no_epoch) > 1

    if required_has_epoch and not current_has_epoch:
        final_current = f'0:{final_current}'
    elif current_has_epoch and not required_has_epoch:
        final_current = current_no_epoch[1]

    required_has_release = bool(RE_VERSION_WITH_RELEASE.match(final_required))
    current_no_release = RE_VERSION_WITH_RELEASE.split(final_current)
    current_has_release = len(current_no_release) > 1

    if required_has_release and not current_has_release:
        final_current = f'{final_current}-1'
    elif current_has_release and not required_has_release:
        final_current = current_no_release[1]

    final_required, final_current = LegacyVersion(
        final_required), LegacyVersion(final_current)

    if operator == '==' or operator == '=':
        return final_current == final_required
    elif operator == '>':
        return final_current > final_required
    elif operator == '>=':
        return final_current >= final_required
    elif operator == '<':
        return final_current < final_required
    elif operator == '<=':
        return final_current <= final_required
예제 #18
0
    def load(cls, path):
        with open(os.path.join(path, cls.envfile)) as inp:
            state = json.load(inp)
            version, data = state['version'], state['data']
        if version > cls.version:
            raise EnvVersionError('saved version exceeds expected version')

        # Upgrade from older versions of the Environment if necessary.

        # v5 converts srcdir and builddir to Path objects internally.
        if version < 5:
            for i in ('srcdir', 'builddir'):
                data[i] = Path(data[i]).to_json()

        # v6 adds persistence for the backend's version and converts bfgpath to
        # a Path object internally.
        if version < 6:
            backend = list_backends()[data['backend']]
            data['backend_version'] = str(backend.version())
            data['bfgpath'] = Path(data['bfgpath']).to_json()

        # v7 replaces bfgpath with bfgdir.
        if version < 7:
            bfgdir = Path.from_json(data['bfgpath']).parent()
            data['bfgdir'] = bfgdir.to_json()
            del data['bfgpath']

        # Now that we've upgraded, initialize the Environment object.
        env = Environment.__new__(Environment)

        for i in ['backend', 'variables']:
            setattr(env, i, data[i])

        setattr(env, 'backend_version', LegacyVersion(data['backend_version']))

        for i in ('bfgdir', 'srcdir', 'builddir'):
            setattr(env, i, Path.from_json(data[i]))

        env.platform = platforms.platform_info(data['platform'])
        env.install_dirs = {
            InstallRoot[k]: Path.from_json(v)
            for k, v in iteritems(data['install_dirs'])
        }

        return env
예제 #19
0
    def _check_version(self, version) -> bool:
        """
        https://www.python.org/dev/peps/pep-0440/
        """
        if isinstance(version, str):
            version = parse(version)

        # if both semver
        if self._semver is not None:
            if not isinstance(version, LegacyVersion):
                return version in self._semver

        # otherwise compare both as legacy
        if self._legacy is not None:
            version = LegacyVersion(str(version))
            return version in self._legacy

        # lovely case, isn't it?
        return False
예제 #20
0
def command_build(buildfile,
                  env,
                  output,
                  inputs=None,
                  implicit=None,
                  order_only=None,
                  commands=None,
                  environ=None,
                  console=True):
    if console:
        rule_name = 'console_command'
        extra_implicit = ['PHONY']

        if not buildfile.has_rule('console_command'):
            # XXX: Can't use SpecifierSet here yet, since those don't work well
            # with LegacyVersions.
            extra_kwargs = {}
            if (env.backend_version
                    and env.backend_version >= LegacyVersion('1.5')):
                extra_kwargs['pool'] = 'console'
            buildfile.rule(name='console_command',
                           command=[[var('cmd')]],
                           **extra_kwargs)

        if not buildfile.has_build('PHONY'):
            buildfile.build(output='PHONY', rule='phony')
    else:
        rule_name = 'command'
        extra_implicit = []

        if not buildfile.has_rule('command'):
            buildfile.rule(name='command', command=var('cmd'))

    buildfile.build(output=output,
                    rule=rule_name,
                    inputs=inputs,
                    implicit=iterutils.listify(implicit) + extra_implicit,
                    order_only=order_only,
                    variables={'cmd': Commands(commands, environ)})
예제 #21
0
    def check_match(self, **kwargs: Any) -> bool:
        """
        Check if the package name and version matches against a blacklisted
        package version specifier.

        Parameters
        ==========
        name: str
            Package name

        version: str
            Package version

        Returns
        =======
        bool:
            True if it matches, False otherwise.
        """
        name = safe_name(kwargs['name']).lower()
        if name not in self.safety_db.keys():
            return False

        version = kwargs['version']
        try:
            version = Version(version)
        except InvalidVersion:  # pragma: no cover
            try:
                version = LegacyVersion(version)
                logger.debug(f'Package {name}=={version} is not a valid PEP 440 version, trying Legacy versioning')
            except InvalidVersion:
                logger.debug(f"Package {name}=={version} has an invalid version")
                return False

        for requirement in self.safety_db[name]:
            if version in requirement.specifier:
                logger.debug(f"Safety DB MATCH: Release {name}=={version} matches specifier {requirement.specifier}")
                return True
        return False
예제 #22
0
import sys, site

# do standard skbuild setup
from packaging.version import LegacyVersion
from skbuild.exceptions import SKBuildError
from skbuild.cmaker import get_cmake_version
from skbuild import setup  # This line replaces 'from setuptools import setup'

# Add CMake as a build requirement if cmake is not installed or too old
setup_requires = []
try:
    if LegacyVersion(get_cmake_version()) < LegacyVersion("3.10"):
        setup_requires.append('cmake>=3.10')
except SKBuildError:
    setup_requires.append('cmake>=3.10')
setup_requires.append('numpy>=1.10')

with open('README.md', 'r') as fh:
    readme_file = fh.readlines()

long_description = ""
for line in readme_file[3:]:
    if line.rstrip() == "Quick Install":
        break
    else:
        long_description += line

long_description += "### Quick Install\n Tasmanian supports `--user` and venv install only, see the on-line documentation for details.\n"

# find out whether this is a virtual environment, real_prefix is an older test, base_refix is the newer one
if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix')
예제 #23
0
파일: setup.py 프로젝트: 00mjk/pycompwa
try:
    from skbuild import setup
except ImportError:
    print('scikit-build is required to build from source.', file=sys.stderr)
    print('Please run:', file=sys.stderr)
    print('', file=sys.stderr)
    print('  python -m pip install scikit-build')
    sys.exit(1)

# Add CMake as a build requirement if cmake is not installed or is too low a
# version
CMAKE_MINIMUM = "3.4"
SETUP_REQUIRES = []
try:
    if LegacyVersion(get_cmake_version()) < LegacyVersion(CMAKE_MINIMUM):
        SETUP_REQUIRES.append('cmake')
except SKBuildError:
    SETUP_REQUIRES.append('cmake')

DATA_FILES = [
    ('pycompwa/', [
        './ComPWA/Physics/particle_list.xml',
    ]),
]

setup(
    name='pycompwa',
    version='0.1-alpha6',
    author='The ComPWA team',
    maintainer_email="*****@*****.**",
예제 #24
0
 def test_specifier_explicit_leacy(self):
     Specifier("==1.0").contains(LegacyVersion("1.0"))
예제 #25
0
import setuptools
import os
import sys
from skbuild import setup
from skbuild.constants import CMAKE_INSTALL_DIR, skbuild_plat_name
from packaging.version import LegacyVersion
from skbuild.exceptions import SKBuildError
from skbuild.cmaker import get_cmake_version

# Add CMake as a build requirement if cmake is not installed or is too low a version
setup_requires = []
try:
    cmake_version = LegacyVersion(get_cmake_version())
    if cmake_version < LegacyVersion("3.5") or cmake_version >= LegacyVersion(
            "3.15"):
        setup_requires.append('cmake<3.15')
except SKBuildError:
    setup_requires.append('cmake<3.15')

# If you want to re-build the cython cpp file (DracoPy.cpp), run:
# cython --cplus -3 -I./_skbuild/linux-x86_64-3.7/cmake-install/include/draco/ ./src/TrakoDracoPy.pyx
# Replace "linux-x86_64-3.6" with the directory under _skbuild in your system
# Draco must already be built/setup.py already be run before running the above command

src_dir = './src'
lib_dir = os.path.abspath(os.path.join(CMAKE_INSTALL_DIR(), 'lib/'))
cmake_args = []
if sys.platform == 'darwin':
    plat_name = skbuild_plat_name()
    sep = [pos for pos, char in enumerate(plat_name) if char == '-']
    assert len(sep) == 2
예제 #26
0
    def test_compare_other(self, op, expected):
        other = pretend.stub(
            **{"__{0}__".format(op): lambda other: NotImplemented})

        assert getattr(operator, op)(LegacyVersion("1"), other) is expected
예제 #27
0
 def test_dunder_op_returns_notimplemented(self, op):
     method = getattr(LegacyVersion, "__{0}__".format(op))
     assert method(LegacyVersion("1"), 1) is NotImplemented
예제 #28
0
 def test_comparison_false(self, left, right, op):
     assert not op(LegacyVersion(left), LegacyVersion(right))
예제 #29
0
 def test_legacy_version_is_postrelease(self, version):
     assert not LegacyVersion(version).is_postrelease
예제 #30
0
 def test_legacy_version_post(self, version):
     assert LegacyVersion(version).post is None