diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml index 175e7dd1c..4d8bd12bb 100644 --- a/.github/workflows/workflow.yml +++ b/.github/workflows/workflow.yml @@ -18,6 +18,7 @@ jobs: - '3.9' - '3.10' - '3.11' + - '3.12' os: - ubuntu-22.04 include: diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 577bcdea0..000000000 --- a/Dockerfile +++ /dev/null @@ -1,34 +0,0 @@ -FROM centos:centos7 -RUN localedef -i en_US -f UTF-8 en_US.UTF-8 -ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' LC_ALL='en_US.UTF-8' - -RUN yum install -y centos-release-scl \ - && yum install -y rh-python36 \ - && yum install -y python-virtualenv \ - && yum install -y openssl-devel git \ - && virtualenv /py2 && /py2/bin/pip install -U pip tox future wheel restructuredtext-lint -RUN /py2/bin/pip install https://github.com/ome/zeroc-ice-py-manylinux/releases/download/0.1.0/zeroc_ice-3.6.5-cp27-cp27mu-manylinux2010_x86_64.whl -ENV PATH=/opt/rh/rh-python36/root/bin/:$PATH -RUN python -m venv /py3 && /py3/bin/pip install -U pip tox future wheel restructuredtext-lint -RUN /py3/bin/pip install https://github.com/ome/zeroc-ice-py-manylinux/releases/download/0.1.0/zeroc_ice-3.6.5-cp36-cp36m-manylinux2010_x86_64.whl - -ENV VIRTUAL_ENV=/py3 -ENV PATH="$VIRTUAL_ENV/bin:$PATH" - -RUN useradd -ms /bin/bash tox -USER tox - -# Optimize for fixing tests -COPY --chown=tox:tox *.py /src/ -COPY --chown=tox:tox README.rst /src -COPY --chown=tox:tox src /src/src -COPY --chown=tox:tox bin /src/bin -WORKDIR /src - -# Copy test-related files and run -COPY --chown=tox:tox ice.config /src/ -COPY --chown=tox:tox *.ini /src/ -COPY --chown=tox:tox test /src/test - -ENV PIP_CACHE_DIR=/tmp/pip-cache -ENTRYPOINT ["/py3/bin/tox"] diff --git a/README.rst b/README.rst index d5a79be34..e19afb50d 100644 --- a/README.rst +++ b/README.rst @@ -19,7 +19,7 @@ Dependencies Direct dependencies of OMERO.py are: - `ZeroC IcePy 3.6`_ -- future +- future (deprecated) - numpy - Pillow >= 10.0.0 diff --git a/docs/conf.py b/docs/conf.py index 57df331c3..d487d8331 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -55,7 +55,7 @@ source_suffix = ".rst" # Build docs without external dependencies -autodoc_mock_imports = ["omero", "omero_ext", "past", "future", +autodoc_mock_imports = ["omero", "omero_ext", "Ice", "IceImport", "Glacier2", "pytest", "appdirs", "IcePy", "omero_version", "IceGrid", "mx", "matplotlib", diff --git a/examples/projection_1.py b/examples/projection_1.py index b4a1a3cee..412adae35 100644 --- a/examples/projection_1.py +++ b/examples/projection_1.py @@ -33,8 +33,7 @@ # @param method the method of projecting (maximum, average) # @return new pixels object containing the projection. # -from builtins import range -from builtins import object + import sys import omero import omero.cli diff --git a/manualtests/populate_roi_test.py b/manualtests/populate_roi_test.py index dfe99f21b..16d39aa46 100644 --- a/manualtests/populate_roi_test.py +++ b/manualtests/populate_roi_test.py @@ -3,7 +3,6 @@ """ ... """ -from __future__ import print_function # # Copyright (C) 2009 University of Dundee. All rights reserved. @@ -24,8 +23,6 @@ # -from builtins import range -from builtins import object import unittest import os diff --git a/setup.py b/setup.py index 233f5be07..2e50a5a57 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,6 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import print_function import glob import sys @@ -18,31 +17,18 @@ find_packages, ) -try: - from StringIO import StringIO - from StringIO import StringIO as BytesIO -except ImportError: - # Python 3 - from io import StringIO - from io import BytesIO +from io import StringIO +from io import BytesIO from shutil import ( copy, rmtree, ) -try: - from urllib.request import urlopen -except ImportError: - # Python 2 - from urllib import urlopen +from urllib.request import urlopen from zipfile import ZipFile -try: - import configparser -except ImportError: - # Python 2 - import ConfigParser as configparser +import configparser def get_blitz_location(): diff --git a/src/omero/__init__.py b/src/omero/__init__.py index baad150a8..cf189ac28 100644 --- a/src/omero/__init__.py +++ b/src/omero/__init__.py @@ -120,14 +120,3 @@ def proxy_to_instance(proxy_string, default=None): raise ClientError(("Invalid proxy string: %s. " "Correct format is Class:ID") % proxy_string) return kls(proxy_string) - -# -# Workaround for warning messages produced in -# code-generated Ice files. -# -if _sys.version_info[:2] == (2, 6): - import warnings - warnings.filterwarnings( - action='ignore', - message='BaseException.message has been deprecated as of Python 2.6', - category=DeprecationWarning) diff --git a/src/omero/callbacks.py b/src/omero/callbacks.py index 51215dc94..09e1105da 100644 --- a/src/omero/callbacks.py +++ b/src/omero/callbacks.py @@ -14,11 +14,6 @@ module for backwards compatibility. """ -from __future__ import division - -from builtins import str -from future.utils import native_str -from past.utils import old_div import Ice import logging import threading @@ -71,7 +66,7 @@ def __init__(self, adapter_or_client, process, poll=True, category=None): self.adapter, self.category = \ adapter_and_category(adapter_or_client, category) - self.id = Ice.Identity(native_str(uuid.uuid4()), self.category) + self.id = Ice.Identity(str(uuid.uuid4()), self.category) self.prx = self.adapter.add(self, self.id) # OK ADAPTER USAGE self.prx = omero.grid.ProcessCallbackPrx.uncheckedCast(self.prx) process.registerCallback(self.prx) @@ -90,7 +85,7 @@ def block(self, ms): except Exception as e: PROC_LOG.warn("Error calling poll: %s" % e) - self.event.wait(old_div(float(ms), 1000)) + self.event.wait(ms / 1000) if self.event.isSet(): return self.result return None @@ -146,7 +141,7 @@ def __init__(self, adapter_or_client, handle, category=None, self.adapter, self.category = \ adapter_and_category(adapter_or_client, category) - self.id = Ice.Identity(native_str(uuid.uuid4()), self.category) + self.id = Ice.Identity(str(uuid.uuid4()), self.category) self.prx = self.adapter.add(self, self.id) # OK ADAPTER USAGE self.prx = omero.cmd.CmdCallbackPrx.uncheckedCast(self.prx) handle.addCallback(self.prx) @@ -259,7 +254,7 @@ def loop(self, loops, ms): if found: return self.getResponse() else: - waited = (old_div(ms, 1000.0)) * loops + waited = (ms / 1000.0) * loops raise omero.LockTimeout( None, None, "Command unfinished after %s seconds" % waited, 5000, int(waited)) @@ -271,7 +266,7 @@ def block(self, ms): which case it returns immediately with true. If false is returned, then the timeout was reached. """ - self.event.wait(old_div(float(ms), 1000)) + self.event.wait(ms / 1000) return self.event.isSet() # diff --git a/src/omero/cli.py b/src/omero/cli.py index 6dbf6ea51..b0d845a8b 100755 --- a/src/omero/cli.py +++ b/src/omero/cli.py @@ -22,21 +22,7 @@ ``cmd.Cmd.cmdloop`` method. """ -from __future__ import division -from __future__ import print_function - -from past.builtins import execfile -from past.builtins import basestring -from future.utils import bytes_to_native_str -from future.utils import isbytes -from future.utils import native_str -from builtins import zip -from builtins import input -from builtins import map -from builtins import str -from builtins import range -from past.utils import old_div -from builtins import object + sys = __import__("sys") cmd = __import__("cmd") @@ -519,9 +505,6 @@ def safePrint(self, text, stream, newline=True): Prints text to a given string, capturing any exceptions. """ try: - if sys.version_info < (3, 0, 0): - if isinstance(text, basestring) and not isinstance(text, unicode): - text = text.encode("utf-8") stream.write(text) if newline: stream.write("\n") @@ -682,7 +665,7 @@ class MyControl(BaseControl): def _configure(self, parser): self.add_error("NAME", 100, "some message: %s") ... - def __call__(self, \*args): + def __call__(self, *args): self.raise_error("NAME", "my text") """ @@ -809,7 +792,7 @@ def _icedata(self, property): nodepath = self._properties()[property] if RELFILE.match(nodepath): - nodedata = old_div(self.dir, path(nodepath)) + nodedata = self.dir / path(nodepath) else: nodedata = path(nodepath) @@ -830,7 +813,7 @@ def _initDir(self): """ props = self._properties() self._nodedata() - logdata = old_div(self.dir, path(props["Ice.StdOut"]).dirname()) + logdata = self.dir / path(props["Ice.StdOut"]).dirname() if not logdata.exists(): self.ctx.out("Initializing %s" % logdata) logdata.makedirs() @@ -862,7 +845,7 @@ def _pid(self): Returns a path of the form _nodedata() / (_node() + ".pid"), i.e. a file named NODENAME.pid in the node's data directory. """ - pidfile = old_div(self._nodedata(), (self._node() + ".pid")) + pidfile = self._nodedata() / (self._node() + ".pid") return pidfile def _cfglist(self): @@ -872,13 +855,13 @@ def _cfglist(self): followed by a file named NODENAME.cfg under the etc/ directory, following by PLATFORM.cfg if it exists. """ - cfgs = old_div(self.dir, "etc") - internal = old_div(cfgs, "internal.cfg") - owncfg = old_div(cfgs, self._node()) + ".cfg" + cfgs = self.dir / "etc" + internal = cfgs / "internal.cfg" + owncfg = cfgs / self._node() + ".cfg" results = [internal, owncfg] # Look for .cfg p_s = platform.system() - p_c = old_div(cfgs, p_s) + ".cfg" + p_c = cfgs / p_s + ".cfg" if p_c.exists(): results.append(p_c) return results @@ -899,7 +882,7 @@ def _intcfg(self): """ intcfg = self.dir / "etc" / "internal.cfg" intcfg.abspath() - return native_str("--Ice.Config=%s" % intcfg) + return "--Ice.Config=%s" % intcfg def _properties(self, prefix=""): """ @@ -913,7 +896,7 @@ def _properties(self, prefix=""): self._props = Ice.createProperties() for cfg in self._cfglist(): try: - self._props.load(native_str(cfg)) + self._props.load(str(cfg)) except Exception: self.ctx.dbg("Complete error: %s" % traceback.format_exc()) self.ctx.die(3, "Could not find file: " + cfg + @@ -1209,7 +1192,7 @@ def __init__(self, prog=sys.argv[0]): self._stack = [] #: List of commands being processed self._client = None #: Single client for all activities #: Paths to be loaded; initially official plugins - self._plugin_paths = [old_div(OMEROCLI, "plugins")] + self._plugin_paths = [OMEROCLI / "plugins"] self._pluginsLoaded = CLI.PluginsLoaded() def assertRC(self): @@ -1340,7 +1323,7 @@ def execute(self, line, previous_args): function returned by argparse. """ - if isinstance(line, basestring): + if isinstance(line, str): if COMMENT.match(line): return # EARLY EXIT! args = shlex.split(line) @@ -1392,7 +1375,7 @@ def execute(self, line, previous_args): elif "p" in debug_opts or "profile" in debug_opts: from hotshot import stats, Profile from omero.util import get_omero_userdir - profile_file = old_div(get_omero_userdir(), "hotshot_edi_stats") + profile_file = get_omero_userdir() / "hotshot_edi_stats" prof = Profile(profile_file) prof.runcall(lambda: args.func(args)) prof.close() @@ -1491,7 +1474,7 @@ def get_config_property_lines(self, root_path): jar_root = root_path / 'lib' / 'server' for component in OMERO_COMPONENTS: from zipfile import ZipFile, is_zipfile, BadZipfile - jar_name = old_div(jar_root, 'omero-{}.jar'.format(component)) + jar_name = jar_root / 'omero-{}.jar'.format(component) if is_zipfile(jar_name): config_name = 'omero-{}.properties'.format(component) try: @@ -1518,8 +1501,8 @@ def readDefaults(self): lines = self.get_config_property_lines(path(self._cwd(None))) defaults = "" for line in lines: - if isbytes(line): - defaults += bytes_to_native_str(line) + if isinstance(line, bytes): + defaults += line.decode("utf-8") else: defaults += line defaults += "\n" @@ -1529,8 +1512,8 @@ def readDefaults(self): def parsePropertyFile(self, data, output): for line in output.splitlines(): - if isbytes(line): - line = bytes_to_native_str(line) + if isinstance(line, bytes): + line = line.decode("utf-8") if line.startswith( "Listening for transport dt_socket at address"): self.dbg( @@ -1554,7 +1537,7 @@ def initData(self, properties=None): from omero.plugins.prefs import getprefs try: - output = getprefs(["get"], str(old_div(path(self._cwd(None)), "lib"))) + output = getprefs(["get"], str(path(self._cwd(None)) / "lib")) except OSError as err: self.err("Error getting preferences") self.dbg(err) @@ -1618,7 +1601,7 @@ def register(self, name, Control, help, epilog=None): self.configure_plugins() def register_only(self, name, Control, help, epilog=None): - """ This method is added to the globals when execfile() is + """ This method is added to the globals when exec() is called on each plugin. A Control class should be passed to the register method which will be added to the CLI. """ @@ -1690,7 +1673,8 @@ def loadpath(self, pathobj): print("Loading %s" % pathobj) try: loc = {"register": self.register_only} - execfile(str(pathobj), loc) + with open(str(pathobj), "r") as f: + exec(f.read(), loc) except KeyboardInterrupt: raise except: @@ -1956,7 +1940,7 @@ def print_report(self, req, rsp, status, detailed): self.ctx.out("Steps: %s" % status.steps) if status.stopTime > 0 and status.startTime > 0: elapse = status.stopTime - status.startTime - self.ctx.out("Elapsed time: %s secs." % (old_div(elapse,1000.0))) + self.ctx.out("Elapsed time: %s secs." % (elapse / 1000.0)) else: self.ctx.out("Unfinished.") self.ctx.out("Flags: %s" % status.flags) @@ -1987,7 +1971,7 @@ def response(self, client, req, loops=8, ms=500, wait=None): self.ctx.out("Exiting immediately") elif wait > 0: ms = wait * 1000 - ms = old_div(ms, loops) + ms = ms // loops self.ctx.out("Waiting %s loops of %s ms" % (ms, loops)) cb.loop(loops, ms) else: diff --git a/src/omero/clients.py b/src/omero/clients.py index b7057fa25..9be32fbb7 100755 --- a/src/omero/clients.py +++ b/src/omero/clients.py @@ -6,13 +6,7 @@ # Use is subject to license terms supplied in LICENSE.txt # # -from __future__ import print_function -from builtins import zip -from builtins import range -from builtins import object -from future.utils import bytes_to_native_str -from future.utils import native_str __save__ = __name__ __name__ = 'omero' try: @@ -34,17 +28,10 @@ import ssl import uuid -from past.builtins import basestring - IceImport.load("Glacier2_Router_ice") import Glacier2 -if sys.version_info >= (3, 0, 0): - # Keep str behavior on Python 2 - from builtins import str - - class BaseClient(object): """ Central client-side blitz entry point, and should be in sync with @@ -143,9 +130,7 @@ def __init__(self, args=None, id=None, host=None, port=None, pmap=None): args = [arg.encode("utf-8") if isinstance(arg, str) else arg for arg in args] - args = [bytes_to_native_str(x) for x in args] - # Under Python 2 this can still leave us with 'unicode' - args = [native_str(x) for x in args] + args = [x.decode("utf-8") for x in args] # Equiv to multiple constructors. ####################### if id is None: @@ -176,7 +161,7 @@ def _repair(self, args, id, host, port, pmap): This allows for simplified usage without parameter names. """ - types = [list, Ice.InitializationData, basestring, int, dict] + types = [list, Ice.InitializationData, str, int, dict] original = [args, id, host, port, pmap] repaired = [None, None, None, None, None] @@ -824,10 +809,7 @@ def sha1(self, filename): """ Calculates the local sha1 for a file. """ - try: - from hashlib import sha1 as sha_new - except ImportError: - from sha import new as sha_new + from hashlib import sha1 as sha_new digest = sha_new() file = open(filename, 'rb') try: @@ -850,7 +832,7 @@ def upload(self, filename, name=None, path=None, type=None, ofile=None, import os import types - if not filename or not isinstance(filename, basestring): + if not filename or not isinstance(filename, str): raise omero.ClientError("Non-null filename must be provided") if not os.path.exists(filename): @@ -964,14 +946,14 @@ def download(self, ofile, filename=None, block_size=1024*1024, filehandle.write(data) except TypeError: # for Python 3.5 - filehandle.write(bytes_to_native_str(data)) + filehandle.write(data.decode("utf-8")) offset += block_size data = prx.read(offset, size - offset) try: filehandle.write(data) except TypeError: # for Python 3.5 - filehandle.write(bytes_to_native_str(data)) + filehandle.write(data.decode("utf-8")) finally: if filename: filehandle.close() diff --git a/src/omero/columns.py b/src/omero/columns.py index 84ae388d7..69c2d52a3 100644 --- a/src/omero/columns.py +++ b/src/omero/columns.py @@ -11,10 +11,6 @@ to PyTables types. """ -from builtins import zip -from builtins import range -from builtins import object -from future.utils import native, bytes_to_native_str, isbytes import omero import Ice import IceImport @@ -286,10 +282,7 @@ def arrays(self): Check for strings longer than the initialised column width This will always return bytes """ - if python_sys.version_info >= (3, 0, 0): - bytevalues = [v.encode() for v in self.values] - else: - bytevalues = self.values + bytevalues = [v.encode() for v in self.values] for bv in bytevalues: if len(bv) > self.size: raise omero.ValidationException( @@ -320,8 +313,8 @@ def descriptor(self, pos): def fromrows(self, rows, field_only=False): AbstractColumn.fromrows(self, rows, field_only=field_only) for i, val in enumerate(self.values): - if isbytes(val): - self.values[i] = bytes_to_native_str(val) + if isinstance(val, bytes): + self.values[i] = val.decode("utf-8") class AbstractArrayColumn(AbstractColumn): diff --git a/src/omero/config.py b/src/omero/config.py index c72f3b45c..41a258bd3 100644 --- a/src/omero/config.py +++ b/src/omero/config.py @@ -1,9 +1,5 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- - -from __future__ import print_function -from __future__ import unicode_literals - # # Copyright 2010 Glencoe Software, Inc. All rights reserved. # Use is subject to license terms supplied in LICENSE.txt @@ -16,7 +12,6 @@ see ticket:2213 - Replacing Java Preferences API """ -from builtins import object, str import os import time import logging diff --git a/src/omero/conversions.py b/src/omero/conversions.py index 3a85d00cf..383d5b432 100644 --- a/src/omero/conversions.py +++ b/src/omero/conversions.py @@ -22,12 +22,7 @@ """ Conversion utilities for changing between units. """ -from __future__ import division - -from builtins import str -from past.utils import old_div -from builtins import object class Conversion(object): """ Base-functor like object which can be used for preparing complex @@ -136,7 +131,7 @@ def unwrap(self, x, original): def __call__(self, original): n = self.unwrap(self.n, original) d = self.unwrap(self.d, original) - return old_div(float(n), d) + return n / d def __str__(self): return "(%s / %s)" % (self.n, self.d) diff --git a/src/omero/gateway/__init__.py b/src/omero/gateway/__init__.py index 229af9d59..2a4f1fdfb 100644 --- a/src/omero/gateway/__init__.py +++ b/src/omero/gateway/__init__.py @@ -1,5 +1,3 @@ -from __future__ import division - # !/usr/bin/env python # -*- coding: utf-8 -*- # @@ -14,44 +12,16 @@ # jason@glencoesoftware.com. # Set up the python include paths -from past.builtins import cmp -from future import standard_library -standard_library.install_aliases() -from builtins import chr -from builtins import map -from builtins import str -from future.utils import native_str -from builtins import range -from past.builtins import basestring -from past.utils import old_div -from builtins import object import os import warnings from collections import defaultdict -try: - from types import IntType, LongType, UnicodeType, ListType - from types import BooleanType, TupleType, StringType, StringTypes -except ImportError: - IntType = int - LongType = int - UnicodeType = str - ListType = list - BooleanType = bool - TupleType = tuple - StringType = str - StringTypes = str - from datetime import datetime from io import StringIO from io import BytesIO -try: - import configparser -except ImportError: - # Python 2 - import ConfigParser as configparser +import configparser import omero import omero.clients @@ -86,27 +56,15 @@ logger = logging.getLogger(__name__) THISPATH = os.path.dirname(os.path.abspath(__file__)) -try: - from PIL import Image, ImageDraw, ImageFont # see ticket:2597 -except: # pragma: nocover - try: - # see ticket:2597 - import Image - import ImageDraw - import ImageFont - except: - logger.error( - 'No Pillow installed, line plots and split channel will fail!') +from PIL import Image, ImageDraw, ImageFont def omero_type(val): """ Converts rtypes from static factory methods: - - StringType to rstring - - UnicodeType to rstring - - BooleanType to rbool - - IntType to rint - - LongType to rlong + - str to rstring + - bool to rbool + - int to rint else return the argument itself @@ -115,16 +73,12 @@ def omero_type(val): :return: matched RType or value """ - if isinstance(val, StringType): + if isinstance(val, str): return rstring(val) - elif isinstance(val, UnicodeType): - return rstring(val.encode('utf-8')) - elif isinstance(val, BooleanType): + elif isinstance(val, bool): return rbool(val) - elif isinstance(val, IntType): + elif isinstance(val, int): return rint(val) - elif isinstance(val, LongType): - return rlong(val) else: return val @@ -348,7 +302,7 @@ def _unwrapunits(self, obj, units=None): return None if units is not None: # If units is an attribute of the same Class as our obj... - if isinstance(units, basestring): + if isinstance(units, str): unitClass = obj.getUnit().__class__ unitEnum = getattr(unitClass, str(units)) # ... we can convert units @@ -397,7 +351,7 @@ def _getChildWrapper(self): if self.CHILD_WRAPPER_CLASS is None: # pragma: no cover raise NotImplementedError( '%s has no child wrapper defined' % self.__class__) - if isinstance(self.CHILD_WRAPPER_CLASS, StringTypes): + if isinstance(self.CHILD_WRAPPER_CLASS, str): # resolve class if hasattr(omero.gateway, self.CHILD_WRAPPER_CLASS): self.__class__.CHILD_WRAPPER_CLASS \ @@ -419,10 +373,10 @@ def _getParentWrappers(self): if self.PARENT_WRAPPER_CLASS is None: # pragma: no cover raise NotImplementedError pwc = self.PARENT_WRAPPER_CLASS - if not isinstance(pwc, ListType): + if not isinstance(pwc, list): pwc = [pwc, ] for i in range(len(pwc)): - if isinstance(pwc[i], StringTypes): + if isinstance(pwc[i], str): # resolve class g = globals() if not pwc[i] in g: # pragma: no cover @@ -521,7 +475,7 @@ def getDate(self): if (self._obj.acquisitionDate.val is not None and self._obj.acquisitionDate.val > 0): t = self._obj.acquisitionDate.val - return datetime.fromtimestamp(old_div(t,1000)) + return datetime.fromtimestamp(t / 1000) except: # object doesn't have acquisitionDate pass @@ -771,7 +725,7 @@ def _listChildren(self, ns=None, val=None, params=None): if ns is not None: query += " and a.ns=:ns" if val is not None: - if isinstance(val, StringTypes): + if isinstance(val, str): params.map["val"] = omero_type(val) query += " and a.textValue=:val" query += " order by c.child.name" @@ -1239,7 +1193,7 @@ def simpleMarshal(self, xtra=None, parents=False): v = v._value if wrapper is not None and v is not None: if wrapper == '': - if isinstance(v, ListType): + if isinstance(v, list): v = [x.simpleMarshal() for x in v] else: v = v.simpleMarshal() @@ -1316,7 +1270,7 @@ def wrap(): def wrap(): rv = getattr(self._obj, attrName) if hasattr(rv, 'val'): - if isinstance(rv.val, StringType): + if isinstance(rv.val, str): if isinstance(rv.val, str): return rv.val else: @@ -1341,7 +1295,7 @@ def wrap(): # since it's not an rtype to unwrap. if not hasattr(rv, "_unit"): rv = rv.val - if isinstance(rv, StringType): + if isinstance(rv, str): try: rv = rv.decode('utf8') except: @@ -1435,7 +1389,7 @@ def creationEventDate(self): """ if self._creationDate is not None: - return datetime.fromtimestamp(old_div(self._creationDate,1000)) + return datetime.fromtimestamp(self._creationDate / 1000) try: if self._obj.details.creationEvent._time is not None: @@ -1448,7 +1402,7 @@ def creationEventDate(self): self._creationDate = self._conn.getQueryService().get( "Event", self._obj.details.creationEvent.id.val, self._conn.SERVICE_OPTS).time.val - return datetime.fromtimestamp(old_div(self._creationDate,1000)) + return datetime.fromtimestamp(self._creationDate / 1000) def updateEventDate(self): """ @@ -1470,7 +1424,7 @@ def updateEventDate(self): t = self._conn.getQueryService().get( "Event", self._obj.details.updateEvent.id.val, self._conn.SERVICE_OPTS).time.val - return datetime.fromtimestamp(old_div(t,1000)) + return datetime.fromtimestamp(t / 1000) # setters are also provided @@ -2217,7 +2171,7 @@ def connect(self, sUuid=None): for key, value in list(self._ic_props.items()): if isinstance(value, str): value = value.encode('utf_8') - self.c.ic.getProperties().setProperty(key, native_str(value)) + self.c.ic.getProperties().setProperty(key, str(value)) if self._anonymous: self.c.ic.getImplicitContext().put( omero.constants.EVENT, 'Internal') @@ -2456,7 +2410,7 @@ def isLeader(self, gid=None): """ if gid is None: gid = self.getEventContext().groupId - if not isinstance(gid, LongType) or not isinstance(gid, IntType): + if not isinstance(gid, int): gid = int(gid) if gid in self.getEventContext().leaderOfGroups: return True @@ -3339,7 +3293,7 @@ def buildQuery(self, obj_type, ids=None, params=None, attributes=None, :return: (query, params, wrapper) """ - if isinstance(obj_type, StringTypes): + if isinstance(obj_type, str): wrapper = KNOWN_WRAPPERS.get(obj_type.lower(), None) if wrapper is None: raise KeyError( @@ -3409,7 +3363,7 @@ def buildQuery(self, obj_type, ids=None, params=None, attributes=None, clauses.append('obj.%s=:%s' % (k, k)) if k == 'id': rv = rlong(v) - elif isinstance(v, IntType): + elif isinstance(v, int): # lookup rint vv rlong from class if wrapper.OMERO_CLASS is not None: klass = getattr(omero.model, @@ -4715,7 +4669,7 @@ def parse_time(c, i): t = c[i] t = unwrap(t) if t is not None: - t = time.localtime(old_div(t, 1000)) + t = time.localtime(t / 1000) t = time.strftime("%Y%m%d", t) return t except: @@ -5015,7 +4969,7 @@ def cf(): try: logger.debug("## - refreshing %s" % (self._func_str or self._service_name)) - obj = conn.c.ic.stringToProxy(native_str(self._obj)) + obj = conn.c.ic.stringToProxy(str(self._obj)) self._obj = self._obj.checkedCast(obj) except Ice.ObjectNotExistException: self._obj = None @@ -5525,7 +5479,7 @@ def getValue(self): :rtype: :class:`datetime.datetime` """ - return datetime.fromtimestamp(old_div(self._obj.timeValue.val, 1000.0)) + return datetime.fromtimestamp(self._obj.timeValue.val / 1000.0) def setValue(self, val): """ @@ -6520,11 +6474,11 @@ def _getQueryString(cls, opts=None): def _letterGridLabel(i): """ Convert number to letter label. E.g. 0 -> 'A' and 100 -> 'CW' """ r = chr(ord('A') + i % 26) - i = old_div(i,26) + i = i // 26 while i > 0: i -= 1 r = chr(ord('A') + i % 26) + r - i = old_div(i,26) + i = i // 26 return r @@ -6792,8 +6746,8 @@ def getName(self): if name is None: if self.startTime is not None and self.endTime is not None: name = "%s - %s" % ( - datetime.fromtimestamp(old_div(self.startTime,1000)), - datetime.fromtimestamp(old_div(self.endTime,1000))) + datetime.fromtimestamp(self.startTime / 1000), + datetime.fromtimestamp(self.endTime / 1000)) else: name = "Run %i" % self.id return name @@ -6812,12 +6766,12 @@ def listParents(self, withlinks=False): def getStartTime(self): """Get the StartTime as a datetime object or None if not set.""" if self.startTime: - return datetime.fromtimestamp(old_div(self.startTime,1000)) + return datetime.fromtimestamp(self.startTime / 1000) def getEndTime(self): """Get the EndTime as a datetime object or None if not set.""" if self.endTime: - return datetime.fromtimestamp(old_div(self.endTime,1000)) + return datetime.fromtimestamp(self.endTime / 1000) PlateAcquisitionWrapper = _PlateAcquisitionWrapper @@ -8095,7 +8049,7 @@ def getAcquisitionDate(self): t = unwrap(self._obj.acquisitionDate) if t is not None and t > 0: try: - return datetime.fromtimestamp(old_div(t,1000)) + return datetime.fromtimestamp(t / 1000) except ValueError: return None @@ -8544,7 +8498,7 @@ def _getProjectedThumbnail(self, size, pos): if len(size) == 1: w = self.getSizeX() h = self.getSizeY() - ratio = old_div(float(w), h) + ratio = w / h if ratio > 1: h = h * size[0] / w w = size[0] @@ -8589,7 +8543,7 @@ def getThumbnail(self, size=(64, 64), z=None, t=None, direct=True, tb = self._prepareTB(rdefId=rdefId) if tb is None: return None - if isinstance(size, IntType): + if isinstance(size, int): size = (size,) if z is not None or t is not None: if z is None: @@ -8663,7 +8617,7 @@ def getPixelRange(self): rp.setPixelsId(pixels_id, True, self._conn.SERVICE_OPTS) pmax = 2 ** (8 * rp.getByteWidth()) if rp.isSigned(): - return (-(old_div(pmax, 2)), old_div(pmax, 2) - 1) + return (- pmax / 2, pmax / 2 - 1) else: return (0, pmax-1) finally: @@ -8786,7 +8740,7 @@ def getZoomLevelScaling(self): rv = {} sizeXList = [level.sizeX for level in levels] for i, level in enumerate(sizeXList): - rv[i] = old_div(float(level),sizeXList[0]) + rv[i] = level / sizeXList[0] return rv @assert_re() @@ -9006,7 +8960,7 @@ def getPixelLine(self, z, t, pos, axis, channels=None, range=None): channels = [x._idx for x in [x for x in self.getChannels() if x.isActive()]] if range is None: range = axis == 'h' and self.getSizeY() or self.getSizeX() - if not isinstance(channels, (TupleType, ListType)): + if not isinstance(channels, (tuple, list)): channels = (channels,) chw = [(x.getWindowMin(), x.getWindowMax()) for x in self.getChannels()] rv = [] @@ -9283,16 +9237,16 @@ def renderBirdsEyeView(self, size): size_x = self.getSizeX() size_y = self.getSizeY() tile_width, tile_height = re.getTileSize() - tiles_wide = math.ceil(old_div(float(size_x), tile_width)) - tiles_high = math.ceil(old_div(float(size_y), tile_height)) + tiles_wide = math.ceil(size_x / tile_width) + tiles_high = math.ceil(size_y / tile_height) # Since the JPEG 2000 algorithm is iterative and rounds pixel # counts at each resolution level we're doing the resulting tile # size calculations in a loop. Also, since the image is physically # tiled the resulting size is a multiple of the tile size and not # the iterative quotient of a 2**(resolutionLevels - 1). for i in range(1, re.getResolutionLevels()): - tile_width = round(old_div(tile_width, 2.0)) - tile_height = round(old_div(tile_height, 2.0)) + tile_width = round(tile_width / 2.0) + tile_height = round(tile_height / 2.0) width = int(tiles_wide * tile_width) height = int(tiles_high * tile_height) jpeg_data = self.renderJpegRegion( @@ -9302,7 +9256,7 @@ def renderBirdsEyeView(self, size): # We've been asked to scale the image by its longest side so we'll # perform that operation until the server has the capability of # doing so. - ratio = old_div(float(size), max(width, height)) + ratio = size / max(width, height) if width > height: size = (int(size), int(height * ratio)) else: @@ -9570,10 +9524,10 @@ def createMovie(self, outpath, zstart, zend, tstart, tend, opts=None): args.append('Canvas_Colour=%s' % opts['minsize'][2]) scalebars = (1, 1, 2, 2, 5, 5, 5, 5, 10, 10, 10, 10) - scalebar = scalebars[max(min(int(old_div(w, 256))-1, len(scalebars)), 1) - 1] + scalebar = scalebars[max(min(int(w // 256)-1, len(scalebars)), 1) - 1] args.append('Scalebar=%d' % scalebar) fsizes = (8, 8, 12, 18, 24, 32, 32, 40, 48, 56, 56, 64) - fsize = fsizes[max(min(int(old_div(w, 256))-1, len(fsizes)), 1) - 1] + fsize = fsizes[max(min(int(w // 256)-1, len(fsizes)), 1) - 1] font = ImageFont.load('%s/pilfonts/B%0.2d.pil' % (THISPATH, fsize)) slides = opts.get('slides', []) for slidepos in range(min(2, len(slides))): @@ -9588,12 +9542,12 @@ def createMovie(self, outpath, zstart, zend, tstart, tend, opts=None): if i == 0: y = 10+j*tsize[1] elif i == 1: - y = old_div(h, 2) - \ + y = h // 2 - \ ((len(wwline)-j)*tsize[1]) + \ - old_div((len(wwline)*tsize[1]),2) + (len(wwline)*tsize[1]) // 2 else: y = h - (len(wwline) - j)*tsize[1] - 10 - draw.text((old_div(w,2)-old_div(tsize[0],2), y), line, font=font) + draw.text((w // 2 - tsize[0] // 2, y), line, font=font) fp = StringIO() slide.save(fp, "JPEG") fileSize = len(fp.getvalue()) @@ -9754,7 +9708,7 @@ def renderSplitChannelImage(self, z, t, compression=0.9, border=2): # Font sizes depends on image width w = self.getSizeX() if w >= 640: - fsize = (int(old_div((w-640),128))*8) + 24 + fsize = (int((w-640) // 128)*8) + 24 if fsize > 64: fsize = 64 elif w >= 512: diff --git a/src/omero/gateway/scripts/dbhelpers.py b/src/omero/gateway/scripts/dbhelpers.py index 9759c58f7..b00f4bd92 100644 --- a/src/omero/gateway/scripts/dbhelpers.py +++ b/src/omero/gateway/scripts/dbhelpers.py @@ -1,10 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import print_function -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import object + import sys sys.path.append('.') @@ -14,11 +10,6 @@ import subprocess import urllib.request, urllib.error, urllib.parse -try: - from types import StringTypes -except ImportError: - StringTypes = str - from omero_ext.path import path BASEPATH = os.path.dirname(os.path.abspath(__file__)) @@ -135,7 +126,7 @@ def check_group_perms(client, group, groupperms): nothing will be checked. """ if groupperms is not None: - if isinstance(group, StringTypes): + if isinstance(group, str): a = client.getAdminService() g = a.lookupGroup(group) else: @@ -156,7 +147,7 @@ def assert_group_perms(client, group, groupperms): """ a = client.getAdminService() try: - if isinstance(group, StringTypes): + if isinstance(group, str): g = a.lookupGroup(group) else: g = group @@ -294,7 +285,7 @@ def create(self, client=None): p.setName(omero.gateway.omero_type(self.name)) p.setDescription(omero.gateway.omero_type(self.name)) if self.create_group: - if isinstance(self.create_group, StringTypes): + if isinstance(self.create_group, str): groupname = self.create_group else: raise ValueError('group must be string') @@ -324,7 +315,7 @@ def __init__(self, name, project, description=None, callback=None): def get(self, client, forceproj=None): if forceproj is None: - if isinstance(self.project, StringTypes): + if isinstance(self.project, str): project = PROJECTS[self.project].get(client) elif isinstance(self.project, ProjectEntry): project = self.project.get(client) @@ -339,7 +330,7 @@ def get(self, client, forceproj=None): return None def create(self): - if isinstance(self.project, StringTypes): + if isinstance(self.project, str): project = PROJECTS[self.project] user = USERS[project.owner] client = user.login() @@ -392,7 +383,7 @@ def get(self, client, forceds=None): return None def create(self): - if isinstance(self.dataset, StringTypes): + if isinstance(self.dataset, str): dataset = DATASETS[self.dataset] project = PROJECTS[dataset.project] client = USERS[project.owner].login() diff --git a/src/omero/gateway/scripts/testdb_create.py b/src/omero/gateway/scripts/testdb_create.py index fc2e32644..8137494d7 100644 --- a/src/omero/gateway/scripts/testdb_create.py +++ b/src/omero/gateway/scripts/testdb_create.py @@ -8,13 +8,7 @@ """ Library for gateway tests """ -from __future__ import print_function -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import range -from builtins import object from io import StringIO from io import BytesIO import omero diff --git a/src/omero/gateway/utils.py b/src/omero/gateway/utils.py index 481ff2063..b22c735a2 100644 --- a/src/omero/gateway/utils.py +++ b/src/omero/gateway/utils.py @@ -23,10 +23,6 @@ # Version: 1.0 # -from builtins import str -from future.utils import native_str -from past.builtins import basestring -from builtins import object import logging import json @@ -88,7 +84,7 @@ def __repr__(self): def __setitem__(self, key, item): """Set key to value as string.""" if self._testItem(item): - super(ServiceOptsDict, self).__setitem__(key, native_str(item)) + super(ServiceOptsDict, self).__setitem__(key, str(item)) logger.debug("Setting %r to %r" % (key, item)) else: raise AttributeError( @@ -174,7 +170,7 @@ def setOmeroShare(self, value=None): def _testItem(self, item): if item is not None and not isinstance(item, bool) and \ - (isinstance(item, basestring) or + (isinstance(item, str) or isinstance(item, int) or isinstance(item, long) or isinstance(item, float)): diff --git a/src/omero/hdfstorageV2.py b/src/omero/hdfstorageV2.py old mode 100644 new mode 100755 index 121994844..f93dee2a7 --- a/src/omero/hdfstorageV2.py +++ b/src/omero/hdfstorageV2.py @@ -9,12 +9,7 @@ """ OMERO HdfStorage Interface """ -from builtins import str -from builtins import zip -from builtins import range -from builtins import object -from future.utils import native, bytes_to_native_str, isbytes -from past.builtins import basestring + import time import numpy import logging @@ -40,14 +35,7 @@ tables = __import__("tables") # Pytables -try: - # long only exists on Python 2 - # Recent versions of PyTables may have treated Python 2 int and long - # identically anyway so treat the same - TABLES_METADATA_INT_TYPES = (int, numpy.int64, long) -except NameError: - TABLES_METADATA_INT_TYPES = (int, numpy.int64) - +TABLES_METADATA_INT_TYPES = (int, numpy.int64) VERSION = '2' @@ -240,7 +228,7 @@ def openfile(self, mode, policy='default'): self.__hdf_path, mode)) mode = "r" - return tables.open_file(native(str(self.__hdf_path)), mode=mode, + return tables.open_file(str(self.__hdf_path), mode=mode, title="OMERO HDF Measurement Storage", rootUEP="/") except (tables.HDF5ExtError, IOError) as e: @@ -313,13 +301,13 @@ def __getversion(self): k = '__version' try: v = self.__mea.attrs[k] - if isinstance(v, basestring): + if isinstance(v, str): return v except KeyError: k = 'version' v = self.__mea.attrs[k] - if isbytes(v): - v = bytes_to_native_str(v) + if isinstance(v, bytes): + v = v.decode("utf-8") if v == 'v1': return '1' @@ -430,12 +418,12 @@ def cols(self, size, current): cols = [] for i in range(len(types)): t = types[i] - if isbytes(t): - t = bytes_to_native_str(t) + if isinstance(t, bytes): + t = t.decode("utf-8") n = names[i] d = descs[i] - if isbytes(d): - d = bytes_to_native_str(d) + if isinstance(d, bytes): + d = d.decode("utf-8") try: col = ic.findObjectFactory(t).create(t) col.name = n @@ -461,10 +449,10 @@ def get_meta_map(self): val = rfloat(val) elif isinstance(val, TABLES_METADATA_INT_TYPES): val = rlong(val) - elif isinstance(val, basestring): - if isbytes(val): - val = bytes_to_native_str(val) + elif isinstance(val, str): val = rstring(val) + elif isinstance(val, bytes): + val = rstring(val.decode("utf-8")) else: raise omero.ValidationException("BAD TYPE: %s" % type(val)) metadata[key] = val diff --git a/src/omero/install/bzip2_tool.py b/src/omero/install/bzip2_tool.py index fafcb2042..1528b5206 100755 --- a/src/omero/install/bzip2_tool.py +++ b/src/omero/install/bzip2_tool.py @@ -10,8 +10,6 @@ comes with PyTables. """ -from __future__ import print_function - import os import sys diff --git a/src/omero/install/config_parser.py b/src/omero/install/config_parser.py index 4e81abb33..750ce5035 100755 --- a/src/omero/install/config_parser.py +++ b/src/omero/install/config_parser.py @@ -23,13 +23,7 @@ Parser for the omero.properties file to generate RST mark up. """ -from __future__ import print_function -from future.utils import bytes_to_native_str -from future.utils import isbytes -from past.builtins import cmp -from builtins import str -from builtins import object class Header(object): def __init__(self, name, reference=None, description=""): """Initialize new configuration property""" @@ -253,8 +247,8 @@ def parse_file(self, argv=None): def parse_lines(self, lines): """Parse the properties from the given configuration file lines""" for line in lines: - if isbytes(line): - line = bytes_to_native_str(line) + if isinstance(line, bytes): + line = line.decode("utf-8") if line.endswith("\n"): line = line[:-1] @@ -419,8 +413,8 @@ def print_rst(self): properties += "%s\n" % underline(len(p.key)) for line in p.txt.split("\n"): if line: - if isbytes(line): - line = bytes_to_native_str(line) + if isinstance(line, bytes): + line = line.decode("utf-8") properties += "%s\n" % (line) else: properties += "\n" diff --git a/src/omero/install/jvmcfg.py b/src/omero/install/jvmcfg.py index 3550a2993..3e22eaeb5 100755 --- a/src/omero/install/jvmcfg.py +++ b/src/omero/install/jvmcfg.py @@ -22,14 +22,7 @@ """ Automatic configuration of memory settings for Java servers. """ -from __future__ import division - -from builtins import str -from builtins import range -from future.utils import bytes_to_native_str -from past.utils import old_div -from builtins import object -from past.builtins import basestring + from shlex import split import logging @@ -47,9 +40,9 @@ def strip_dict(map, prefix=("omero", "jvmcfg"), suffix=(), limit=1): of elements that are allowed in the new key after stripping prefix and suffix. """ - if isinstance(prefix, basestring): + if isinstance(prefix, str): prefix = tuple(prefix.split(".")) - if isinstance(suffix, basestring): + if isinstance(suffix, str): suffix = tuple(suffix.split(".")) rv = dict() if not map: @@ -200,7 +193,7 @@ def _system_memory_mb_psutil(self): try: import psutil pymem = psutil.virtual_memory() - return (old_div(pymem.free,1000000), old_div(pymem.total,1000000)) + return (pymem.free // 1000000, pymem.total // 1000000) except ImportError: LOGGER.debug("No psutil installed") return None @@ -214,7 +207,8 @@ def _system_memory_mb_java(self): jars = str(cwd / "lib" / "server") + "/*" cmd = ["ome.services.util.JvmSettingsCheck", "--psutil"] p = omero.java.popen(["-cp", str(jars)] + cmd) - o, e = list(map(bytes_to_native_str, p.communicate())) + o = p.communicate()[0].decode("utf-8") + e = p.communicate()[1].decode("utf-8") if p.poll() != 0: LOGGER.warn("Failed to invoke java:\nout:%s\nerr:%s", @@ -231,13 +225,13 @@ def _system_memory_mb_java(self): rv[parts[0]] = parts[1] try: - free = old_div(int(rv["Free"]), 1000000) + free = int(rv["Free"]) // 1000000 except: LOGGER.warn("Failed to parse Free from %s", rv) free = 2000 try: - total = old_div(int(rv["Total"]), 1000000) + total = int(rv["Total"]) // 1000000 except: LOGGER.warn("Failed to parse Total from %s", rv) total = 4000 @@ -493,7 +487,7 @@ def usage_charts(path, from pylab import text points = 200 - x = array([old_div(2 ** (old_div(x, points)), 1000) + x = array([2 ** (x // points // 1000) for x in range(min*points, max*points)]) y_configs = ( (Settings({}), 'A'), diff --git a/src/omero/install/logs_library.py b/src/omero/install/logs_library.py index 3929e0055..40a1c21f1 100755 --- a/src/omero/install/logs_library.py +++ b/src/omero/install/logs_library.py @@ -12,11 +12,7 @@ The format expected is defined for Python in omero.util.configure_logging. """ -from __future__ import division -from __future__ import print_function -from builtins import object -from past.utils import old_div import numpy as np import matplotlib.pyplot as plt import matplotlib.lines as lines @@ -38,7 +34,7 @@ def parse_time(value): """ parts = value.split(",") value = parts[0] - millis = old_div(float(parts[1]), 1000.0) + millis = parts[1] / 1000.0 t = mktime(strptime(value, "%Y-%m-%d %H:%M:%S")) t = float(t) t += millis diff --git a/src/omero/install/perf_test.py b/src/omero/install/perf_test.py index 03999acaa..4eadec195 100755 --- a/src/omero/install/perf_test.py +++ b/src/omero/install/perf_test.py @@ -6,12 +6,6 @@ # Add: plotting # -from __future__ import division -from __future__ import print_function -from builtins import str -from builtins import range -from builtins import object -from past.utils import old_div import re import os import sys @@ -124,7 +118,7 @@ def execute(self, ctx): def create_obj(self, ctx, name): id = None - id_path = old_div(ctx.dir, ("%s.id" % name)) + id_path = ctx.dir / ("%s.id" % name) prop = self.props.get(name) # Do nothing if not in props if prop is None: @@ -175,8 +169,8 @@ def _op_Import(self, ctx): raise BadPath("File does not exist: %s" % self.path) f = str(p.abspath()) - out = old_div(ctx.dir, ("import_%s.out" % ctx.count)) - err = old_div(ctx.dir, ("import_%s.err" % ctx.count)) + out = ctx.dir / ("import_%s.out" % ctx.count) + err = ctx.dir / ("import_%s.err" % ctx.count) args = ["import", "---file=%s" % str(out), "---errs=%s" % str(err), "-s", ctx.host(), "-k", ctx.key(), f] @@ -231,14 +225,14 @@ def add_reporter(self, reporter): self.reporters.append(reporter) def setup_dir(self): - self.dir = old_div(path.path("."), ("perfdir-%s" % os.getpid())) + self.dir = path.path(".") / ("perfdir-%s" % os.getpid()) if self.dir.exists(): raise Exception("%s exists!" % self.dir) self.dir.makedirs() # Adding a file logger handler = logging.handlers.RotatingFileHandler( - str(old_div(self.dir, "perf.log")), maxBytes=10000000, backupCount=5) + str(self.dir / "perf.log"), maxBytes=10000000, backupCount=5) handler.setLevel(logging.DEBUG) formatter = logging.Formatter(omero.util.LOGFORMAT) handler.setFormatter(formatter) @@ -289,7 +283,7 @@ def __init__(self, ctx=None): def __call__(self, line): - (old_div(self.ctx.dir,"line.log")).write_text(line, append=True) + (self.ctx.dir / "line.log").write_text(line, append=True) item = Item(line) if item.comment(): @@ -314,7 +308,7 @@ def __call__(self, line): values["errs"] = errs if loops > 1: - values["avg"] = old_div(total, loops) + values["avg"] = total // loops stop = time.time() total += (stop - start) @@ -341,13 +335,13 @@ def __init__(self, dir=None): if dir is None: self.stream = sys.stdout else: - self.file = str(old_div(dir, "report.csv")) + self.file = str(dir / "report.csv") self.stream = open(self.file, "w") print("Command,Start,Stop,Elapsed,Average,Values", file=self.stream) def report(self, command, start, stop, loops, values): print("%s,%s,%s,%s,%s,%s" % ( - command, start, stop, (stop-start), old_div((stop-start),loops), values), file=self.stream) + command, start, stop, (stop-start), (stop-start) // loops, values), file=self.stream) self.stream.flush() @@ -355,7 +349,7 @@ class HdfReporter(Reporter): def __init__(self, dir): import tables - self.file = str(old_div(dir, "report.hdf")) + self.file = str(dir / "report.hdf") # Temporarily support old and new PyTables methods try: @@ -381,7 +375,7 @@ def report(self, command, start, stop, loops, values): self.row["Start"] = start self.row["Stop"] = stop self.row["Elapsed"] = (stop-start) - self.row["Average"] = old_div((stop-start),loops) + self.row["Average"] = (stop-start) // loops self.row["Values"] = values self.row.append() self.hdf.flush() diff --git a/src/omero/install/versions.py b/src/omero/install/versions.py index 98544ad46..2991edc41 100755 --- a/src/omero/install/versions.py +++ b/src/omero/install/versions.py @@ -8,7 +8,6 @@ Version comparison functionality """ -from __future__ import print_function import re import logging diff --git a/src/omero/install/win_set_path.py b/src/omero/install/win_set_path.py index 13e245879..9bd908555 100755 --- a/src/omero/install/win_set_path.py +++ b/src/omero/install/win_set_path.py @@ -11,10 +11,7 @@ Omero installation on Windows, since relative paths are not supported. """ -from __future__ import print_function - -from builtins import str import sys from omero_ext.path import path import fileinput @@ -23,7 +20,7 @@ def win_set_path(new_name=dummy, old_name=r"c:\omero_dist", dir=path(".")): - """ + r""" Parses the Windows cfg and xml files and replaces the default "c:\omero_dist" with the given value. @@ -80,7 +77,7 @@ def win_set_path(new_name=dummy, old_name=r"c:\omero_dist", dir=path(".")): print("Failed to set path: ", e) sys.exit(1) - print("""Usage: %s [oldname] newname + print(r"""Usage: %s [oldname] newname Replaces the [oldname] entries in the Windows configuration files with [newname]. By default, [oldname] is set to "c:\omero_dist" diff --git a/src/omero/main.py b/src/omero/main.py index 578c39bef..673276f73 100755 --- a/src/omero/main.py +++ b/src/omero/main.py @@ -10,7 +10,6 @@ """ Python driver for OMERO """ -from __future__ import print_function import logging import os diff --git a/src/omero/plugins/_metadata_deprecated.py b/src/omero/plugins/_metadata_deprecated.py index 3832b67a0..5fe3f5dab 100755 --- a/src/omero/plugins/_metadata_deprecated.py +++ b/src/omero/plugins/_metadata_deprecated.py @@ -9,13 +9,6 @@ Metadata plugin """ -from __future__ import division - -from builtins import str -from future.utils import native_str -from builtins import range -from past.utils import old_div -from builtins import object import logging import mimetypes import os @@ -507,7 +500,7 @@ def populate(self, args): ms = 0 else: ms = 5000 - loops = int(old_div((wait * 1000), ms)) + 1 + loops = int((wait * 1000) // ms) + 1 ctx.write_to_omero(batch_size=args.batch, loops=loops, ms=ms) def rois(self, args): @@ -644,7 +637,7 @@ def pixelsize(self, args): pixel.setPhysicalSizeZ(omero.model.LengthI(args.z, unit)) groupId = pixels[0].getDetails().getGroup().getId().getValue() - ctx = {'omero.group': native_str(groupId)} + ctx = {'omero.group': str(groupId)} conn.getUpdateService().saveArray(pixels, ctx) diff --git a/src/omero/plugins/admin.py b/src/omero/plugins/admin.py index 97af80af6..5f1cf36d7 100755 --- a/src/omero/plugins/admin.py +++ b/src/omero/plugins/admin.py @@ -11,14 +11,7 @@ This is a python wrapper around icegridregistry/icegridnode for master and various other tools needed for administration. """ -from __future__ import division -from __future__ import print_function - -from builtins import str -from future.utils import bytes_to_native_str -from future.utils import isbytes -from past.utils import old_div -from builtins import object + import re import os import sys @@ -696,11 +689,11 @@ def _node(self, omero_node=None): def _get_etc_dir(self): """Return path to directory containing configuration files""" - return old_div(self.ctx.dir, "etc") + return self.ctx.dir / "etc" def _get_grid_dir(self): """Return path to directory containing Gridconfiguration files""" - return old_div(self._get_etc_dir(), "grid") + return self._get_etc_dir() / "grid" def _get_templates_dir(self): """Return path to directory containing templates""" @@ -729,7 +722,7 @@ def _descript(self, args): __d__ = "default.xml" if self._isWindows(): __d__ = "windefault.xml" - descript = old_div(self._get_grid_dir(), __d__) + descript = self._get_grid_dir() / __d__ self.ctx.err("No descriptor given. Using %s" % os.path.sep.join(["etc", "grid", __d__])) return descript @@ -996,7 +989,7 @@ def loops_and_wait(self, args): args.wait = DEFAULT_WAIT total_secs = args.wait - loop_secs = old_div(total_secs, 30.0) + loop_secs = total_secs // 30.0 return 30, loop_secs, "%s seconds" % total_secs @with_config @@ -1113,7 +1106,7 @@ def jvmcfg(self, args, config): self.ctx.out("%s=%s" % (k, sb)) def _get_omero_properties(self): - omero_props_file = old_div(self._get_etc_dir(), "omero.properties") + omero_props_file = self._get_etc_dir() / "omero.properties" pp = PropertyParser() omero_props = dict( (p.key, p.val) for p in pp.parse_file(omero_props_file)) @@ -1164,7 +1157,7 @@ def rewrite(self, args, config, force=False): # Get some defaults from omero.properties config_props = self._get_omero_properties() - generated = old_div(self._get_grid_dir(), "templates.xml") + generated = self._get_grid_dir() / "templates.xml" if generated.exists(): generated.remove() config2 = omero.config.ConfigXml(str(generated)) @@ -1224,8 +1217,8 @@ def copy_template(input_file, output_dir, post_process=None): """Replace templates""" with open(input_file) as template: data = template.read() - output_file = path(old_div(output_dir, - os.path.basename(input_file))) + output_file = path(output_dir / + os.path.basename(input_file)) if output_file.exists(): output_file.remove() with open(output_file, 'w') as f: @@ -1236,14 +1229,14 @@ def copy_template(input_file, output_dir, post_process=None): f.write(data) # Regenerate various configuration files from templates - for cfg_file in glob(old_div(self._get_templates_dir(), "*.cfg")): + for cfg_file in glob(self._get_templates_dir() / "*.cfg"): copy_template(cfg_file, self._get_etc_dir()) for xml_file in glob( self._get_templates_dir() / "grid" / "*default.xml"): copy_template( - xml_file, old_div(self._get_etc_dir(), "grid"), + xml_file, self._get_etc_dir() / "grid", lambda xml: _process_xml(xml, node_descriptors)) - ice_config = old_div(self._get_templates_dir(), "ice.config") + ice_config = self._get_templates_dir() / "ice.config" substitutions['@omero.master.host@'] = config.get( 'omero.master.host', config.get('Ice.Default.Host', 'localhost')) copy_template(ice_config, self._get_etc_dir()) @@ -1260,7 +1253,7 @@ def diagnostics(self, args, config): from omero.install.jvmcfg import read_settings self.check_access(os.R_OK) - templates = old_div(self._get_grid_dir(), "templates.xml") + templates = self._get_grid_dir() / "templates.xml" if templates.exists(): template_xml = XML(templates.text()) try: @@ -1293,10 +1286,11 @@ def version(cmd): return False p.wait() - io = list(map(bytes_to_native_str, p.communicate())) + stdout_data = p.communicate()[0].decode("utf-8") + stderr_data = p.communicate()[1].decode("utf-8") try: - v = io[0].split() - v.extend(io[1].split()) + v = stdout_data.split() + v.extend(stderr_data.split()) v = "".join(v) m = re.match(r"^\D*(\d[.\d]+\d)\D?.*$", v) v = "%-10s" % m.group(1) @@ -1432,12 +1426,12 @@ def parse_logs(): files.sort() for x in files: self._item("Log files", x) - self._exists(old_div(log_dir, x)) + self._exists(log_dir / x) self._item("Log files", "Total size") sz = 0 for x in log_dir.walkfiles(): sz += x.size - self.ctx.out("%-.2f MB" % (old_div(float(sz), 1000000.0))) + self.ctx.out("%-.2f MB" % (sz / 1000000.0)) self.ctx.out("") # Parsing well known issues @@ -1715,7 +1709,7 @@ def can_access(self, filepath, mask=os.R_OK | os.W_OK): def check_access(self, mask=os.R_OK | os.W_OK, config=None): """Check that 'var' is accessible by the current user.""" - var = old_div(self.ctx.dir, 'var') + var = self.ctx.dir / 'var' if not os.path.exists(var): self.ctx.out("Creating directory %s" % var) os.makedirs(var) @@ -1775,8 +1769,8 @@ def checkice(self, args=None): def _check(msg, vers): compat = ice_compatibility.split(".") - if isbytes(vers): - vers = bytes_to_native_str(vers) + if isinstance(vers, bytes): + vers = vers.decode("utf-8") vers = vers.split(".") if compat[0:2] != vers[0:2]: self.ctx.die(164, "%s is not compatible with %s: %s" @@ -1803,8 +1797,8 @@ def open_config(self, unused=None): Callers are responsible for closing the returned ConfigXml object. """ - cfg_xml = old_div(self._get_grid_dir(), "config.xml") - cfg_tmp = old_div(self._get_grid_dir(), "config.xml.tmp") + cfg_xml = self._get_grid_dir() / "config.xml" + cfg_tmp = self._get_grid_dir() / "config.xml.tmp" grid_dir = self._get_grid_dir() if not cfg_xml.exists() and self.can_access(grid_dir): if cfg_tmp.exists() and self.can_access(cfg_tmp): diff --git a/src/omero/plugins/basics.py b/src/omero/plugins/basics.py index e20ec9dec..085d098a2 100644 --- a/src/omero/plugins/basics.py +++ b/src/omero/plugins/basics.py @@ -17,9 +17,7 @@ The help, quit, and version plugins are self-explanatory. """ -from __future__ import print_function -from past.builtins import cmp from glob import glob import sys diff --git a/src/omero/plugins/db.py b/src/omero/plugins/db.py index 18350a08d..ba7682f32 100644 --- a/src/omero/plugins/db.py +++ b/src/omero/plugins/db.py @@ -25,11 +25,7 @@ Plugin read by omero.cli.Cli during initialization. The method(s) defined here will be added to the Cli class for later use. """ -from __future__ import division -from future.utils import bytes_to_native_str -from future.utils import isbytes -from past.utils import old_div from omero.cli import BaseControl from omero.cli import CLI @@ -44,10 +40,6 @@ import sys import time -if sys.version_info >= (3, 0, 0): - # Keep str behavior on Python 2 - from builtins import str - HELP = """Database tools for creating scripts, setting passwords, etc.""" @@ -172,8 +164,8 @@ def _copy(self, input_path, output, func, cfg=None): def _make_replace(self, root_pass, db_vers, db_patch): def fix(str_in): - if isbytes(str_in): - str_in = bytes_to_native_str(str_in) + if isinstance(str_in, bytes): + return str_in.decode("utf-8") return str_in def replace_method(str_in): str_out = str_in.replace("@ROOTPASS@", fix(root_pass)) @@ -214,7 +206,7 @@ def _create(self, sql_directory, db_vers, db_patch, password_hash, args, script = "" else: script = "%s__%s.sql" % (db_vers, db_patch) - location = old_div(path.getcwd(), script) + location = path.getcwd() / script try: output = open(location, 'w', encoding='utf-8') except TypeError: @@ -223,8 +215,8 @@ def _create(self, sql_directory, db_vers, db_patch, password_hash, args, try: dbprofile = self._db_profile() - header = old_div(sql_directory, ("%s-header.sql" % dbprofile)) - footer = old_div(sql_directory, ("%s-footer.sql" % dbprofile)) + header = sql_directory / ("%s-header.sql" % dbprofile) + footer = sql_directory / ("%s-footer.sql" % dbprofile) if header.exists(): # 73 multiple DB support. OMERO 4.3+ cfg = { @@ -232,8 +224,8 @@ def _create(self, sql_directory, db_vers, db_patch, password_hash, args, "DIR": sql_directory, "SCRIPT": script} self._copy(header, output, str, cfg) - self._copy(old_div(sql_directory,"schema.sql"), output, str) - self._copy(old_div(sql_directory,"views.sql"), output, str) + self._copy(sql_directory / "schema.sql", output, str) + self._copy(sql_directory / "views.sql", output, str) self._copy( footer, output, self._make_replace(password_hash, db_vers, db_patch), cfg) @@ -255,11 +247,11 @@ def _create(self, sql_directory, db_vers, db_patch, password_hash, args, BEGIN; """ % (time.ctime(time.time()), sql_directory, script)) - self._copy(old_div(sql_directory,"schema.sql"), output, str) + self._copy(sql_directory / "schema.sql", output, str) self._copy( - old_div(sql_directory,"data.sql"), output, + sql_directory / "data.sql", output, self._make_replace(password_hash, db_vers, db_patch)) - self._copy(old_div(sql_directory,"views.sql"), output, str) + self._copy(sql_directory / "views.sql", output, str) output.write("COMMIT;\n") finally: diff --git a/src/omero/plugins/download.py b/src/omero/plugins/download.py index 70b71b245..d92af120a 100755 --- a/src/omero/plugins/download.py +++ b/src/omero/plugins/download.py @@ -12,7 +12,6 @@ defined here will be added to the Cli class for later use. """ -from builtins import str import sys import omero import os @@ -44,18 +43,13 @@ class StdOutHandle(): """ - File handle for writing bytes to std.out in python 2 and python 3 + File handle for writing bytes to std.out """ # https://github.com/pexpect/pexpect/pull/31/files @staticmethod def write(b): # Handle stdout.write for bytes - try: - # Try writing bytes... python 2 - return sys.stdout.write(b) - except TypeError: - # python 3: If String was expected, convert to String - return sys.stdout.write(b.decode('ascii', 'replace')) + return sys.stdout.write(b.decode('ascii', 'replace')) class DownloadControl(BaseControl): diff --git a/src/omero/plugins/export.py b/src/omero/plugins/export.py index 00e50a76b..014c49999 100644 --- a/src/omero/plugins/export.py +++ b/src/omero/plugins/export.py @@ -9,7 +9,6 @@ Startup plugin for command-line exporter """ -from builtins import str import os import sys diff --git a/src/omero/plugins/fs.py b/src/omero/plugins/fs.py index 0a42c017a..957b15f45 100755 --- a/src/omero/plugins/fs.py +++ b/src/omero/plugins/fs.py @@ -22,15 +22,7 @@ """ fs plugin for querying repositories, filesets, and the like. """ -from __future__ import division -from __future__ import print_function - -from past.builtins import cmp -from builtins import zip -from builtins import str -from builtins import map -from builtins import object -from past.utils import old_div + import platform import sys @@ -614,16 +606,12 @@ def repos(self, args): """ from omero.grid import ManagedRepositoryPrx as MRepo - from functools import cmp_to_key - - def my_cmp(a, b): - return cmp(a[0].id.val, b[0].id.val) client = self.ctx.conn(args) shared = client.sf.sharedResources() repos = shared.repositories() repos = list(zip(repos.descriptions, repos.proxies)) - repos.sort(key = cmp_to_key(my_cmp)) + repos.sort(key=lambda repo: repo[0].id.val) tb = self._table(args) tb.cols(["Id", "UUID", "Type", "Path"]) @@ -834,7 +822,7 @@ def get_managed_repo(self, client): shared = client.sf.sharedResources() repos = shared.repositories() repos = list(zip(repos.descriptions, repos.proxies)) - repos.sort(lambda a, b: cmp(a[0].id.val, b[0].id.val)) + repos.sort(key=lambda repo: repo[0].id.val) for idx, pair in enumerate(repos): if MRepo.checkedCast(pair[1]): @@ -925,7 +913,7 @@ def _to_units(self, size, units): oneK = 1024.0 powers = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5} if units in list(powers.keys()): - return round(old_div(size,oneK**powers[units]), 1) + return round(size / oneK**powers[units], 1) else: raise ValueError("Unrecognized units: ", units) @@ -1390,46 +1378,46 @@ def print_report(self): metrics_keys = set(self.metrics) if set(['UPLOAD', 'UPLOAD_C']) <= metrics_keys: - time = old_div(self.metrics['UPLOAD'], 1000.0) + time = self.metrics['UPLOAD'] / 1000.0 count = self.metrics['UPLOAD_C'] plural = "s" if count > 1 else "" print((" upload time of {0:6.2f}s for " "{1} file{2} ({3:.3f}s/file)") - .format(time, count, plural, old_div(time,count))) + .format(time, count, plural, time / count)) - time = old_div(self.metrics['SET_ID'], 1000.0) + time = self.metrics['SET_ID'] / 1000.0 print(" setId time of {0:6.2f}s".format(time)) - time = old_div(self.metrics['METADATA'], 1000.0) + time = self.metrics['METADATA'] / 1000.0 print(" metadata time of {0:6.2f}s".format(time)) if set(['PIXELDATA', 'PIXELDATA_C']) <= metrics_keys: - time = old_div(self.metrics['PIXELDATA'], 1000.0) + time = self.metrics['PIXELDATA'] / 1000.0 count = self.metrics['PIXELDATA_C'] plural = "s" if count > 1 else "" print((" pixels time of {0:6.2f}s for " "{1} plane{2} ({3:.3f}s/plane)") - .format(time, count, plural, old_div(time,count))) + .format(time, count, plural, time / count)) if 'OVERLAY' in metrics_keys: - time = old_div(self.metrics['OVERLAY'], 1000.0) + time = self.metrics['OVERLAY'] / 1000.0 print(" overlays time of {0:6.2f}s".format(time)) if set(['RDEF', 'RDEF_C']) <= metrics_keys: - time = old_div(self.metrics['RDEF'], 1000.0) + time = self.metrics['RDEF'] / 1000.0 count = self.metrics['RDEF_C'] plural = "s" if count > 1 else "" print((" rdefs time of {0:6.2f}s for " "{1} rendering setting{2} ({3:.3f}s/rdef)") - .format(time, count, plural, old_div(time,count))) + .format(time, count, plural, time / count)) if set(['THUMBNAIL', 'THUMBNAIL_C']) <= metrics_keys: - time = old_div(self.metrics['THUMBNAIL'], 1000.0) + time = self.metrics['THUMBNAIL'] / 1000.0 count = self.metrics['THUMBNAIL_C'] plural = "s" if count > 1 else "" print(("thumbnail time of {0:6.2f}s for " "{1} thumbnail{2} ({3:.3f}s/thumbnail)") - .format(time, count, plural, old_div(time,count))) + .format(time, count, plural, time / count)) def print_summary(self): """ diff --git a/src/omero/plugins/group.py b/src/omero/plugins/group.py index 6db46777c..c2a6d2b96 100755 --- a/src/omero/plugins/group.py +++ b/src/omero/plugins/group.py @@ -9,7 +9,6 @@ Group administration plugin """ -from builtins import str import sys from omero.cli import UserGroupControl, CLI, ExceptionHandler, admin_only diff --git a/src/omero/plugins/hql.py b/src/omero/plugins/hql.py index 2a94eb3fb..d85c0e4fd 100755 --- a/src/omero/plugins/hql.py +++ b/src/omero/plugins/hql.py @@ -11,11 +11,7 @@ Plugin read by omero.cli.Cli during initialization. The method(s) defined here will be added to the Cli class for later use. """ -from __future__ import division -from builtins import str -from builtins import range -from past.utils import old_div from omero.cli import BaseControl, CLI import time import sys @@ -197,7 +193,7 @@ def unwrap(self, object, cache=None): if isinstance(unwrapped, IObject): rv = "%s:%s" % (unwrapped.__class__.__name__, unwrapped.id.val) elif isinstance(object, RTimeI): - rv = time.ctime(old_div(unwrapped,1000.0)) + rv = time.ctime(unwrapped / 1000.0) elif isinstance(object, Details): owner = None group = None diff --git a/src/omero/plugins/import.py b/src/omero/plugins/import.py index 04555bcbc..7f73ce661 100644 --- a/src/omero/plugins/import.py +++ b/src/omero/plugins/import.py @@ -23,13 +23,7 @@ Startup plugin for command-line importer. """ -from __future__ import division -from __future__ import print_function -from builtins import str -from past.utils import old_div -from past.builtins import basestring -from builtins import object from io import BytesIO import os import csv @@ -162,13 +156,13 @@ def build_arg_list(self, key, val=NO_ARG): if len(key) == 1: arg_list.append("-"+key) if val != NO_ARG: - if isinstance(val, basestring): + if isinstance(val, str): arg_list.append(val) else: key = key.replace("_", "-") if val == NO_ARG: arg_list.append("--%s" % key) - elif isinstance(val, basestring): + elif isinstance(val, str): arg_list.append( "--%s=%s" % (key, val)) else: @@ -518,11 +512,11 @@ def _get_classpath_logback(self, args): omero_java_dir, omero_java_txt = self._userdir_jars() client_dir = omero_java_dir - etc_dir = old_div(self.ctx.dir, "etc") + etc_dir = self.ctx.dir / "etc" if args.logback: xml_file = path(args.logback) else: - xml_file = old_div(etc_dir, "logback-cli.xml") + xml_file = etc_dir / "logback-cli.xml" classpath = [] if client_dir and client_dir.exists(): @@ -577,7 +571,7 @@ def _userdir_jars(self, parentonly=False): return None, omero_java_txt def download_omero_java(self, version_or_uri): - if re.match("^\w+://", version_or_uri): + if re.match(r"^\w+://", version_or_uri): omero_java_zip = version_or_uri else: omero_java_zip = OMERO_JAVA_ZIP.format(version=version_or_uri) diff --git a/src/omero/plugins/ldap.py b/src/omero/plugins/ldap.py index 4310b7926..7b71b5df9 100644 --- a/src/omero/plugins/ldap.py +++ b/src/omero/plugins/ldap.py @@ -10,7 +10,6 @@ User administration plugin (LDAP extension) """ -from builtins import str import sys from omero.cli import CLI, ExceptionHandler, admin_only, UserGroupControl diff --git a/src/omero/plugins/node.py b/src/omero/plugins/node.py index fd9339fb3..8578b6208 100755 --- a/src/omero/plugins/node.py +++ b/src/omero/plugins/node.py @@ -11,11 +11,7 @@ This is a python wrapper around icegridnode. """ -from __future__ import division -from __future__ import print_function -from builtins import str -from past.utils import old_div from omero.cli import BaseControl, CLI, NonZeroReturnCode from omero.util import tail_lines import os @@ -74,7 +70,7 @@ def _handleNZRC(self, nzrc): """ props = self._properties() self.ctx.rv = nzrc.rv - myoutput = old_div(self.dir, path(props["Ice.StdErr"])) + myoutput = self.dir / path(props["Ice.StdErr"]) if not myoutput.exists(): pass else: diff --git a/src/omero/plugins/obj.py b/src/omero/plugins/obj.py index e9fd44226..db0e3eed5 100755 --- a/src/omero/plugins/obj.py +++ b/src/omero/plugins/obj.py @@ -27,8 +27,6 @@ """ -from builtins import str -from builtins import object import re import sys import shlex diff --git a/src/omero/plugins/perf.py b/src/omero/plugins/perf.py index e03cc4244..11be3979c 100755 --- a/src/omero/plugins/perf.py +++ b/src/omero/plugins/perf.py @@ -12,7 +12,6 @@ Plugin read by omero.cli.Cli during initialization. The method(s) defined here will be added to the Cli class for later use. """ -from __future__ import print_function import sys from omero.cli import BaseControl, CLI diff --git a/src/omero/plugins/prefs.py b/src/omero/plugins/prefs.py index d19acd5e6..e084dd3e4 100755 --- a/src/omero/plugins/prefs.py +++ b/src/omero/plugins/prefs.py @@ -11,11 +11,7 @@ The pref plugin makes use of prefs.class from the common component. """ -from __future__ import division -from builtins import zip -from builtins import str -from past.utils import old_div import sys import traceback import os @@ -524,7 +520,7 @@ def lock(self, args, config): @with_rw_config def upgrade(self, args, config): self.ctx.out("Importing pre-4.2 preferences") - txt = getprefs(["get"], str(old_div(self.ctx.dir, "lib"))) + txt = getprefs(["get"], str(self.ctx.dir / "lib")) # Handle all lines before updating config in case of error. new_config = dict(config) @@ -601,7 +597,7 @@ def handle_line(self, line, config, keys): config[_key] = _new def old(self, args): - self.ctx.out(getprefs(args.target, str(old_div(self.ctx.dir, "lib")))) + self.ctx.out(getprefs(args.target, str(self.ctx.dir / "lib"))) try: register("config", PrefsControl, HELP) diff --git a/src/omero/plugins/script.py b/src/omero/plugins/script.py index 57db08190..d6569b770 100755 --- a/src/omero/plugins/script.py +++ b/src/omero/plugins/script.py @@ -18,10 +18,7 @@ The first parameter, the script itself, should be natively executable on a given platform i.e. invokable by subprocess.call([file,...]) """ -from __future__ import print_function -from builtins import str -from builtins import object import re import os import sys @@ -288,10 +285,7 @@ def demo(self, args): from omero.util.temp_files import create_path t = create_path("Demo_Script", ".py") - try: - from hashlib import sha1 as sha_new - except ImportError: - from sha import new as sha_new + from hashlib import sha1 as sha_new digest = sha_new() digest.update(DEMO_SCRIPT.encode('utf-8')) diff --git a/src/omero/plugins/search.py b/src/omero/plugins/search.py index 53c031a51..289dbc39b 100755 --- a/src/omero/plugins/search.py +++ b/src/omero/plugins/search.py @@ -11,7 +11,6 @@ """ -from builtins import str import sys import time diff --git a/src/omero/plugins/sessions.py b/src/omero/plugins/sessions.py index c99adbd15..371d7fe0f 100644 --- a/src/omero/plugins/sessions.py +++ b/src/omero/plugins/sessions.py @@ -24,10 +24,7 @@ Plugin read by omero.cli.Cli during initialization. The method(s) defined here will be added to the Cli class for later use. """ -from __future__ import division -from builtins import str -from past.utils import old_div import datetime import os import sys @@ -310,8 +307,8 @@ def open(self, args): sess = svc.createSessionWithTimeout(p, (int(args.timeout) * 1000)) sessId = sess.getUuid().val - tti = old_div(sess.getTimeToIdle().val, 1000) - ttl = old_div(sess.getTimeToLive().val, 1000) + tti = sess.getTimeToIdle().val / 1000 + ttl = sess.getTimeToLive().val / 1000 msg = "Session created for user %s" % username if groupname: @@ -727,7 +724,7 @@ def timeout(self, args): if args.seconds is None: # Query only - secs = old_div(unwrap(obj.timeToIdle),1000.0) + secs = unwrap(obj.timeToIdle) / 1000.0 self.ctx.out(secs) return secs @@ -768,7 +765,7 @@ def list(self, args): grp = a_s.getEventContext().groupName s_s = rv[0].sf.getSessionService() started = s_s.getSession(uuid).started.val - started = time.ctime(old_div(started, 1000.0)) + started = time.ctime(started / 1000.0) finally: if rv: rv[0].closeSession() @@ -845,7 +842,7 @@ def who(self, args): for k, v in sorted(data.items()): try: if k.endswith("Time"): - t = old_div(v, 1000.0) + t = v / 1000.0 t = time.localtime(t) v = time.strftime('%Y-%m-%d %H:%M:%S', t) except: @@ -854,7 +851,7 @@ def who(self, args): results["name"].append(ec.userName) results["group"].append(ec.groupName) if s is not None: - t = old_div(s.started.val, 1000.0) + t = s.started.val / 1000.0 t = time.localtime(t) t = time.strftime("%Y-%m-%d %H:%M:%S", t) if uuid == ec.sessionUuid: diff --git a/src/omero/plugins/submit.py b/src/omero/plugins/submit.py index 494b280f3..c9b06b282 100755 --- a/src/omero/plugins/submit.py +++ b/src/omero/plugins/submit.py @@ -11,9 +11,7 @@ Plugin read by omero.cli.Cli during initialization. The method(s) defined here will be added to the Cli class for later use. """ -from __future__ import print_function -from builtins import str from omero.cli import BaseControl, CLI import sys diff --git a/src/omero/plugins/tag.py b/src/omero/plugins/tag.py index 524851a5e..abbfd256d 100644 --- a/src/omero/plugins/tag.py +++ b/src/omero/plugins/tag.py @@ -9,14 +9,7 @@ """ Tag plugin for command-line tag manipulation """ -from __future__ import division - -from builtins import input -from builtins import map -from builtins import str -from past.utils import old_div -from builtins import object -import builtins + import platform import subprocess import sys @@ -519,7 +512,7 @@ def create_tag(self, name, description, text="tag"): (the default). If we were creating a tagset, this could be "tag set". """ if name is None: - name = builtins.input("Please enter a name for this %s: " % text) + name = input("Please enter a name for this %s: " % text) if name is not None and name != '': tag = TagAnnotationI() @@ -732,7 +725,7 @@ def listsets(self, args): self.width, self.console_length = self.determine_console_size() if args.desc: - max_field_width = int((old_div((self.width - max_id_width), 2.0)) - 2) + max_field_width = int(((self.width - max_id_width) / 2.0) - 2) else: max_field_width = self.width - max_id_width - 2 diff --git a/src/omero/processor.py b/src/omero/processor.py index 978dc80e1..7e93b7981 100755 --- a/src/omero/processor.py +++ b/src/omero/processor.py @@ -9,12 +9,6 @@ OMERO Grid Processor """ -from __future__ import division -from builtins import str -from builtins import range -from future.utils import native_str -from past.utils import old_div -from builtins import object import os import time import signal @@ -60,13 +54,13 @@ class WithGroup(object): def __init__(self, service, group_id): self._service = service - self._group_id = native_str(group_id) + self._group_id = str(group_id) def _get_ctx(self, group=None): ctx = self._service.ice_getCommunicator()\ .getImplicitContext().getContext() ctx = dict(ctx) - ctx["omero.group"] = native_str(group) + ctx["omero.group"] = str(group) return ctx def __getattr__(self, name): @@ -186,10 +180,10 @@ def make_env(self): def make_files(self): self.dir = create_path("process", ".dir", folder=True) - self.script_path = old_div(self.dir, "script") - self.config_path = old_div(self.dir, "config") - self.stdout_path = old_div(self.dir, "out") - self.stderr_path = old_div(self.dir, "err") + self.script_path = self.dir / "script" + self.config_path = self.dir / "config" + self.stdout_path = self.dir / "out" + self.stderr_path = self.dir / "err" def make_config(self): """ @@ -705,7 +699,7 @@ def make_files(self): in ordert to append a ".m" """ ProcessI.make_files(self) - self.script_path = old_div(self.dir, "script.m") + self.script_path = self.dir / "script.m" def command(self): """ diff --git a/src/omero/rtypes.py b/src/omero/rtypes.py old mode 100644 new mode 100755 index 8200437bc..5b729810c --- a/src/omero/rtypes.py +++ b/src/omero/rtypes.py @@ -16,8 +16,6 @@ omero.rtypes as well as the omero/rtypes.{h,cpp} files. """ -from builtins import str -from past.builtins import basestring, long import omero import Ice import IceImport @@ -49,11 +47,9 @@ def rtype(val): return rbool(val) elif isinstance(val, int): return rint(val) - elif isinstance(val, long): # Maintains Py2 compatibility - return rlong(val) elif isinstance(val, float): return rfloat(val) - elif isinstance(val, basestring): + elif isinstance(val, str) or isinstance(val, bytes): return rstring(val) elif isinstance(val, omero.model.IObject): return robject(val) @@ -275,7 +271,7 @@ def rclass(val): return remptyclass elif isinstance(val, omero.RClass): return val - elif isinstance(val, basestring): + elif isinstance(val, str): if len(val) == 0: return remptyclass else: @@ -293,13 +289,10 @@ def rstring(val): return remptystr elif isinstance(val, omero.RString): return val - elif isinstance(val, basestring): + elif isinstance(val, str) or isinstance(val, bytes): if len(val) == 0: return remptystr else: - if sys.version_info < (3, 0, 0): - if isinstance(val, str): - val = val.encode("utf-8") return RStringI(val) else: return rstring(str(val)) @@ -557,7 +550,7 @@ def ice_preMarshal(self): class RLongI(omero.RLong): def __init__(self, value): - omero.RLong.__init__(self, long(value)) + omero.RLong.__init__(self, int(value)) def getValue(self, current=None): return self._val @@ -613,7 +606,7 @@ def ice_preMarshal(self): class RTimeI(omero.RTime): def __init__(self, value): - omero.RTime.__init__(self, long(value)) + omero.RTime.__init__(self, int(value)) def getValue(self, current=None): return self._val @@ -1157,7 +1150,7 @@ def __init__(self, arg=None, **kwargs): def _validate(self): for k, v in list(self._val.items()): - if not isinstance(k, basestring): + if not isinstance(k, str): raise ValueError("Key of wrong type: %s" % type(k)) if v is not None and not isinstance(v, omero.RType): raise ValueError("Value of wrong type: %s" % type(v)) diff --git a/src/omero/tables.py b/src/omero/tables.py index 63f077509..d37a4c58e 100644 --- a/src/omero/tables.py +++ b/src/omero/tables.py @@ -8,11 +8,6 @@ """ OMERO Grid Processor """ -from __future__ import division -from builtins import str -from builtins import range -from future.utils import native_str -from past.utils import old_div import Ice import time import traceback @@ -162,7 +157,7 @@ def __close_file(self): gid = unwrap(self.file_obj.details.group.id) client_uuid = self.factory.ice_getIdentity().category[8:] ctx = { - "omero.group": native_str(gid), + "omero.group": str(gid), omero.constants.CLIENTUUID: client_uuid} try: # Size to reset the server object to (must be checked after @@ -426,7 +421,7 @@ def __init__( wait = float(self.communicator.getProperties().getPropertyWithDefault( "omero.repo.wait", "1")) - per_loop = old_div(wait, retries) + per_loop = wait / retries exc = None for x in range(retries): @@ -475,7 +470,7 @@ def _get_uuid(self): """ cfg = self.ctx.getSession().getConfigService() self.db_uuid = cfg.getDatabaseUuid() - self.instance = old_div(self.repo_cfg, self.db_uuid) + self.instance = self.repo_cfg / self.db_uuid def _get_repo(self): """ @@ -484,7 +479,7 @@ def _get_repo(self): create a proxy for the InternalRepository attached to that. """ - uuidfile = old_div(self.instance, "repo_uuid") + uuidfile = self.instance / "repo_uuid" if not uuidfile.exists(): msg = "%s doesn't exist" % uuidfile raise IOError(msg) diff --git a/src/omero/testlib/__init__.py b/src/omero/testlib/__init__.py index a0b316479..cee6e6207 100644 --- a/src/omero/testlib/__init__.py +++ b/src/omero/testlib/__init__.py @@ -23,15 +23,7 @@ Library for integration tests """ -from __future__ import division -from __future__ import print_function - -from builtins import str -from future.utils import native_str -from past.builtins import basestring -from builtins import range -from past.utils import old_div -from builtins import object + import os import platform import locale @@ -636,7 +628,7 @@ def group_and_name(cls, group): else: group = admin.getGroup(group.id.val) name = group.name.val - elif isinstance(group, basestring): + elif isinstance(group, str): name = group group = admin.lookupGroup(name) elif isinstance(group, Experimenter): @@ -663,7 +655,7 @@ def user_and_name(cls, user): else: user = admin.getExperimenter(user.id.val) name = user.omeName.val - elif isinstance(user, basestring): + elif isinstance(user, str): name = user user = admin.lookupExperimenter(name) elif isinstance(user, ExperimenterGroup): @@ -818,7 +810,7 @@ def do_submit(self, request, client, test_should_pass=True, sf = client.sf if omero_group is not None: - prx = sf.submit(request, {'omero.group': native_str(omero_group)}) + prx = sf.submit(request, {'omero.group': str(omero_group)}) else: prx = sf.submit(request) @@ -1301,8 +1293,8 @@ def raw(self, command, args, client=None): def create_test_dir(self): folder = create_path(folder=True) - (old_div(folder, "a.fake")).touch() - (old_div(folder, "b.fake")).touch() + (folder / "a.fake").touch() + (folder / "b.fake").touch() return folder def create_fileset(self, folder): diff --git a/src/omero/testlib/cli.py b/src/omero/testlib/cli.py index 5d13057ce..54ab1eed0 100644 --- a/src/omero/testlib/cli.py +++ b/src/omero/testlib/cli.py @@ -20,7 +20,6 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest import omero diff --git a/src/omero/util/OmeroPopo.py b/src/omero/util/OmeroPopo.py index 5cbe2c4d4..34d5e9cc2 100644 --- a/src/omero/util/OmeroPopo.py +++ b/src/omero/util/OmeroPopo.py @@ -19,12 +19,6 @@ # @author Donald MacDonald      # donald@lifesci.dundee.ac.uk -from __future__ import division -from __future__ import print_function - -from builtins import range -from past.utils import old_div -from builtins import object import math import numpy @@ -805,7 +799,7 @@ def containsPoints(self): o = (majr[1] - majl[1]) a = (majr[0] - majl[0]) h = math.sqrt(o * o + a * a) - majorAxisAngle = math.asin(old_div(o, h)) + majorAxisAngle = math.asin(o / h) boundingBoxMinX = min(lt[0], rt[0], lb[0], rb[0]) boundingBoxMaxX = max(lt[0], rt[0], lb[0], rb[0]) boundingBoxMinY = min(lt[1], rt[1], lb[1], rb[1]) @@ -827,8 +821,8 @@ def containsPoints(self): math.sin(majorAxisAngle) newY = -dx * math.sin(majorAxisAngle) + \ dy * math.cos(majorAxisAngle) - val = old_div((newX * newX), (radiusx * radiusx)) + \ - old_div((newY * newY), (radiusy * radiusy)) + val = (newX * newX) / (radiusx * radiusx) + \ + (newY * newY) / (radiusy * radiusy) if(val <= 1): points[(int(dx + cx), int(dy + cy))] = 1 return points @@ -1013,7 +1007,7 @@ def getBoundingRectangle(self): # @return See above. def toCoords(self, ptsList): coords = [] - for index in range(old_div(len(ptsList), 2)): + for index in range(len(ptsList) // 2): coords.append( (int(ptsList[index * 2]), int(ptsList[index * 2 + 1]))) return coords @@ -1043,7 +1037,7 @@ def inPolygon(self, p): angle = 0.0 polypoints = self.getPoints() polygon = [] - for index in range(0, old_div(len(polypoints), 2)): + for index in range(0, len(polypoints) // 2): polygon.append( (int(polypoints[index * 2]), int(polypoints[index * 2 + 1]))) @@ -1345,7 +1339,7 @@ def containsPoints(self): o = (majr[1] - majl[1]) a = (majr[0] - majl[0]) h = math.sqrt(o * o + a * a) - angle = math.asin(old_div(o, h)) + angle = math.asin(o / h) boundingBoxMinX = min(lt[0], rt[0], lb[0], rb[0]) boundingBoxMaxX = max(lt[0], rt[0], lb[0], rb[0]) boundingBoxMinY = min(lt[1], rt[1], lb[1], rb[1]) diff --git a/src/omero/util/ROIDrawingUtils.py b/src/omero/util/ROIDrawingUtils.py index 76eeafc2e..82af3bab3 100644 --- a/src/omero/util/ROIDrawingUtils.py +++ b/src/omero/util/ROIDrawingUtils.py @@ -53,10 +53,7 @@ Example code to draw a polyline on an image an display it in PIL:: - try: - from PIL import Image, ImageDraw # see ticket:2597 - except ImportError: - import Image, ImageDraw # see ticket:2597 + from PIL import Image, ImageDraw import ROI_utils import ROIDrawingUtils @@ -72,12 +69,7 @@ """ -from builtins import object -try: - from PIL import Image, ImageDraw # see ticket:2597 -except ImportError: - import Image - import ImageDraw # see ticket:2597 +from PIL import Image, ImageDraw import warnings diff --git a/src/omero/util/ROI_utils.py b/src/omero/util/ROI_utils.py index d45a30559..b3659648f 100644 --- a/src/omero/util/ROI_utils.py +++ b/src/omero/util/ROI_utils.py @@ -35,12 +35,6 @@ the ROIDrawingCanvas. """ -from __future__ import division -from builtins import str -from builtins import map -from builtins import range -from past.utils import old_div -from builtins import object from omero.model.enums import UnitsLength from omero.model import LengthI from omero.model import EllipseI @@ -813,7 +807,7 @@ def stringToTupleList(self, pointString): elements = [] list = pointString.split(',') numTokens = len(list) - for tokenPair in range(0, old_div(numTokens, 2)): + for tokenPair in range(0, numTokens // 2): elements.append( (int(list[tokenPair * 2]), int(list[tokenPair * 2 + 1]))) return elements @@ -901,7 +895,7 @@ def stringToTupleList(self, pointString): elements = [] list = pointString.split(',') numTokens = len(list) - for tokenPair in range(0, old_div(numTokens, 2)): + for tokenPair in range(0, numTokens // 2): elements.append( (int(list[tokenPair * 2]), int(list[tokenPair * 2 + 1]))) return elements diff --git a/src/omero/util/__init__.py b/src/omero/util/__init__.py index d13069142..be9ff6c9e 100644 --- a/src/omero/util/__init__.py +++ b/src/omero/util/__init__.py @@ -7,11 +7,6 @@ # Use is subject to license terms supplied in LICENSE.txt # -from __future__ import division -from builtins import str -from future.utils import native_str -from past.utils import old_div -from builtins import object from appdirs import user_data_dir, user_cache_dir import os import sys @@ -98,13 +93,13 @@ def configure_server_logging(props): log_timed = props.getPropertyWithDefault( "omero.logging.timedlog", "False")[0] in ('T', 't') log_num = int( - props.getPropertyWithDefault("omero.logging.lognum", native_str(LOGNUM))) + props.getPropertyWithDefault("omero.logging.lognum", str(LOGNUM))) log_size = int( - props.getPropertyWithDefault("omero.logging.logsize", native_str(LOGSIZE))) + props.getPropertyWithDefault("omero.logging.logsize", str(LOGSIZE))) log_num = int( - props.getPropertyWithDefault("omero.logging.lognum", native_str(LOGNUM))) + props.getPropertyWithDefault("omero.logging.lognum", str(LOGNUM))) log_level = int( - props.getPropertyWithDefault("omero.logging.level", native_str(LOGLEVEL))) + props.getPropertyWithDefault("omero.logging.level", str(LOGLEVEL))) configure_logging(log_dir, log_name, loglevel=log_level, maxBytes=log_size, backupCount=log_num, time_rollover=log_timed) @@ -206,7 +201,7 @@ def internal_service_factory(communicator, user="root", group=None, retries=6, implicit_ctx.put(omero.constants.CLIENTUUID, client_uuid) else: if not implicit_ctx.containsKey(omero.constants.CLIENTUUID): - client_uuid = native_str(uuid.uuid4()) + client_uuid = str(uuid.uuid4()) implicit_ctx.put(omero.constants.CLIENTUUID, client_uuid) while tryCount < retries: @@ -292,7 +287,7 @@ def load_dotted_class(dotted_class): try: parts = dotted_class.split(".") pkg = ".".join(parts[0:-2]) - mod = native_str(parts[-2]) + mod = str(parts[-2]) kls = parts[-1] got = __import__(pkg, fromlist=[mod]) got = getattr(got, mod) @@ -464,7 +459,7 @@ def waitOnStartup(self): try: self.logger.info("Waiting %s ms on startup" % ms) - self.stop_event.wait(old_div(ms, 1000)) + self.stop_event.wait(ms // 1000) except: self.logger.debug(exc_info=1) @@ -854,7 +849,7 @@ def get_omero_userdir(): elif omero_userdir == "": return path.path(user_data_dir(*APPDIR_DEFAULTS)) else: - return old_div(path.path(get_user_dir()), "omero") + return path.path(get_user_dir()) / "omero" def get_omero_user_cache_dir(): diff --git a/src/omero/util/cleanse.py b/src/omero/util/cleanse.py index 1e7f874d6..1cc5658c7 100644 --- a/src/omero/util/cleanse.py +++ b/src/omero/util/cleanse.py @@ -3,7 +3,6 @@ """ Reconcile and cleanse where necessary an OMERO data directory of orphaned data. """ -from __future__ import print_function # # Copyright (c) 2009-2016 University of Dundee. All rights reserved. @@ -29,8 +28,6 @@ # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. -from builtins import range -from builtins import object import omero.clients import omero import sys @@ -165,20 +162,20 @@ def do_cleanse(self): if object_id.val not in existing_ids: if object_id.val == -1: if self.dry_run: - print(" \_ %s (ignored/keep)" % path) + print(r" \_ %s (ignored/keep)" % path) else: size = os.stat(path)[ST_SIZE] self.cleansed.append(path) self.bytes_cleansed = size if self.dry_run: - print(" \_ %s (remove)" % path) + print(r" \_ %s (remove)" % path) else: try: os.unlink(path) except OSError as e: print(e) elif self.dry_run: - print(" \_ %s (keep)" % path) + print(r" \_ %s (keep)" % path) self.deferred_paths = list() def finalize(self): @@ -263,7 +260,7 @@ def delete_empty_dirs(repo, root, client, dry_run): if dry_run: for directory in to_delete: - print(" \_ %s%s (remove)" % (root, directory)) + print(r" \_ %s%s (remove)" % (root, directory)) elif to_delete: # probably less than a screenful batch_size = 20 diff --git a/src/omero/util/concurrency.py b/src/omero/util/concurrency.py index 6c48cfdeb..43964cf7e 100644 --- a/src/omero/util/concurrency.py +++ b/src/omero/util/concurrency.py @@ -15,13 +15,8 @@ import omero.util import logging.handlers -try: - from threading import _Event - from threading import _Timer -except ImportError: - # Python3 - from threading import Event as _Event - from threading import Timer as _Timer +from threading import Event as _Event +from threading import Timer as _Timer def get_event(name="Unknown"): diff --git a/src/omero/util/decorators.py b/src/omero/util/decorators.py index fbebc4db0..fbc0807c2 100644 --- a/src/omero/util/decorators.py +++ b/src/omero/util/decorators.py @@ -9,7 +9,6 @@ """ OMERO Decorators """ -from builtins import object import time import logging import traceback diff --git a/src/omero/util/figureUtil.py b/src/omero/util/figureUtil.py old mode 100644 new mode 100755 index 9c95f08c4..ef2af53d7 --- a/src/omero/util/figureUtil.py +++ b/src/omero/util/figureUtil.py @@ -28,16 +28,8 @@ A collection of utility methods used by Figure scripts for producing publication type of figures. """ -from __future__ import division -from builtins import str -from builtins import range -from past.utils import old_div -try: - from PIL import Image, ImageDraw # see ticket:2597 -except ImportError: - import Image - import ImageDraw +from PIL import Image, ImageDraw WHITE = (255, 255, 255) @@ -166,27 +158,27 @@ def formatTime(seconds, timeUnits): elif timeUnits == "SECS": label = "%d" % int(round(seconds)) elif timeUnits == "MINS": - mins = old_div(float(seconds), float(60)) + mins = seconds / 60 label = "%d" % int(round(mins)) elif timeUnits == "HOURS": - hrs = old_div(float(seconds), float(3600)) + hrs = seconds / 3600 label = "%d" % int(round(hrs)) elif timeUnits == "MINS_SECS": - mins = old_div(seconds, 60) + mins = seconds // 60 secs = round(seconds % 60) label = "%d:%02d" % (mins, secs) elif timeUnits == "HOURS_MINS": - hrs = old_div(seconds, 3600) - mins = round(old_div((seconds % 3600), 60)) + hrs = seconds // 3600 + mins = round((seconds % 3600) // 60) label = "%d:%02d" % (hrs, mins) elif timeUnits == "HOURS_MINS_SECS": - hrs = old_div(seconds, 3600) - mins = old_div((seconds % 3600), 60) + hrs = seconds // 3600 + mins = (seconds % 3600) // 60 secs = round(seconds % (3600 * 60)) label = "%d:%02d:%02d" % (hrs, mins, secs) elif timeUnits == "HOURS_MINS_SECS_MILLIS": - hrs = old_div(seconds, 3600) - mins = old_div((seconds % 3600), 60) + hrs = seconds // 3600 + mins = (seconds % 3600) // 60 secs = (seconds % (3600 * 60)) label = "%d:%02d:%05.2f" % (hrs, mins, secs) else: @@ -297,7 +289,7 @@ def getVerticalLabels(labels, font, textGap): for label in labels: box = font.getbbox(label) width = box[2] - box[0] - indent = old_div((maxWidth - width), 2) + indent = (maxWidth - width) // 2 textdraw.text((indent, py), label, font=font, fill=(0, 0, 0)) py += textHeight + textGap return textCanvas.rotate(90) diff --git a/src/omero/util/imageUtil.py b/src/omero/util/imageUtil.py old mode 100644 new mode 100755 index 3aa32a46c..9ab89e790 --- a/src/omero/util/imageUtil.py +++ b/src/omero/util/imageUtil.py @@ -28,17 +28,8 @@ A collection of utility methods based on the Python Imaging Library (PIL) used for making figures. """ -from __future__ import division - -from future import standard_library -standard_library.install_aliases() -from past.utils import old_div -try: - from PIL import Image, ImageDraw, ImageFont # see ticket:2597 -except ImportError: - import Image - import ImageDraw - import ImageFont # see ticket:2597 + +from PIL import Image, ImageDraw, ImageFont import os.path import omero.gateway @@ -160,7 +151,7 @@ def paintThumbnailGrid(thumbnailStore, length, spacing, pixelIds, colCount, # work out how many rows and columns are needed for all the images imgCount = len(pixelIds) - rowCount = (old_div(imgCount, colCount)) + rowCount = imgCount // colCount # check that we have enough rows and cols... while (colCount * rowCount) < imgCount: rowCount += 1 @@ -174,7 +165,7 @@ def paintThumbnailGrid(thumbnailStore, length, spacing, pixelIds, colCount, if leftLabel is not None and rowCount == 0: rowCount = 1 if fontsize is None: - fontsize = old_div(length, 10) + 5 + fontsize = length // 10 + 5 font = getFont(fontsize) if leftLabel: box = font.getbbox(leftLabel) @@ -206,7 +197,7 @@ def paintThumbnailGrid(thumbnailStore, length, spacing, pixelIds, colCount, draw = ImageDraw.Draw(textCanvas) box = font.getbbox(leftLabel) textWidth = box[2] - box[0] - textX = old_div((labelCanvasWidth - textWidth), 2) + textX = (labelCanvasWidth - textWidth) // 2 draw.text((textX, spacing), leftLabel, font=font, fill=textColour) verticalCanvas = textCanvas.rotate(90) pasteImage(verticalCanvas, canvas, 0, 0) @@ -318,8 +309,8 @@ def getZoomFactor(imageSize, maxW, maxH): warnings.warn( "This module is deprecated as of OMERO 5.3.0", DeprecationWarning) imageW, imageH = imageSize - zoomW = old_div(float(imageW), float(maxW)) - zoomH = old_div(float(imageH), float(maxH)) + zoomW = imageW / maxW + zoomH = imageH / maxH return max(zoomW, zoomH) @@ -340,8 +331,8 @@ def resizeImage(image, maxW, maxH): return image # find which axis requires the biggest zoom (smallest relative max # dimension) - zoomW = old_div(float(imageW), float(maxW)) - zoomH = old_div(float(imageH), float(maxH)) + zoomW = imageW / maxW + zoomH = imageH / maxH zoom = max(zoomW, zoomH) if zoomW >= zoomH: # size is defined by width maxH = int(imageH // zoom) # calculate the new height diff --git a/src/omero/util/image_utils.py b/src/omero/util/image_utils.py old mode 100644 new mode 100755 index a92816d6b..3398cee82 --- a/src/omero/util/image_utils.py +++ b/src/omero/util/image_utils.py @@ -21,17 +21,8 @@ """ Utility methods for dealing with scripts. """ -from __future__ import division - -from future import standard_library -standard_library.install_aliases() -from past.utils import old_div -try: - from PIL import Image, ImageDraw, ImageFont # see ticket:2597 -except ImportError: - import Image - import ImageDraw - import ImageFont # see ticket:2597 + +from PIL import Image, ImageDraw, ImageFont import os.path import omero.gateway @@ -105,7 +96,7 @@ def paint_thumbnail_grid(thumbnail_store, length, spacing, pixel_ids, # work out how many rows and columns are needed for all the images img_count = len(pixel_ids) - row_count = (old_div(img_count, col_count)) + row_count = img_count // col_count # check that we have enough rows and cols... while (col_count * row_count) < img_count: row_count += 1 @@ -119,7 +110,7 @@ def paint_thumbnail_grid(thumbnail_store, length, spacing, pixel_ids, if left_label is not None and row_count == 0: row_count = 1 if fontsize is None: - fontsize = old_div(length, 10) + 5 + fontsize = length // 10 + 5 font = get_font(fontsize) if left_label: box = font.getbbox(leftLabel) @@ -152,7 +143,7 @@ def paint_thumbnail_grid(thumbnail_store, length, spacing, pixel_ids, draw = ImageDraw.Draw(text_canvas) box = font.getbbox(leftLabel) text_width = box[2] - box[0] - text_x = old_div((label_canvas_width - text_width), 2) + text_x = (label_canvas_width - text_width) // 2 draw.text((text_x, spacing), left_label, font=font, fill=text_color) vertical_canvas = text_canvas.rotate(90) paste_image(vertical_canvas, canvas, 0, 0) @@ -244,8 +235,8 @@ def get_zoom_factor(image_size, max_width, max_height): within max width and height """ image_width, imageheight = image_size - zoom_width = old_div(float(image_width), float(max_width)) - zoom_height = old_div(float(imageheight), float(max_height)) + zoom_width = image_width / max_width + zoom_height = imageheight / max_height return max(zoom_width, zoom_height) @@ -264,8 +255,8 @@ def resize_image(image, max_width, max_height): return image # find which axis requires the biggest zoom (smallest relative max # dimension) - zoom_width = old_div(float(image_width), float(max_width)) - zoom_height = old_div(float(image_height), float(max_height)) + zoom_width = image_width / max_width + zoom_height = image_height / max_height zoom = max(zoom_width, zoom_height) if zoom_width >= zoom_height: # size is defined by width max_height = int(image_height // zoom) # calculate the new height diff --git a/src/omero/util/import_candidates.py b/src/omero/util/import_candidates.py index 414d532ec..6b410aa45 100644 --- a/src/omero/util/import_candidates.py +++ b/src/omero/util/import_candidates.py @@ -12,7 +12,6 @@ """ -from builtins import str import omero from omero.util.temp_files import create_path, remove_path diff --git a/src/omero/util/importperf.py b/src/omero/util/importperf.py index c75986720..8ee11b43f 100755 --- a/src/omero/util/importperf.py +++ b/src/omero/util/importperf.py @@ -4,8 +4,6 @@ """ Performs various performance metrics and reports on OMERO.importer log files. """ -from __future__ import division -from __future__ import print_function # Copyright (C) 2009 University of Dundee @@ -24,9 +22,6 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. -from builtins import str -from past.utils import old_div -from builtins import object import re import sys @@ -108,8 +103,8 @@ class ImporterLog(object): # Regular expression for matching log4j log lines log_regex = re.compile( r'^(?P\S+\s+\S+)\s+(?P\d+)\s+' - '(?P\[.*?\])\s+(?P\S+)\s+(?P\S+)\s+-\s+' - '(?P.*)$') + r'(?P\[.*?\])\s+(?P\S+)\s+(?P\S+)\s+-\s+' + r'(?P.*)$') # Regular expression for matching possible OMERO.importer status messages status_regex = re.compile(r'^[A-Z_]*') @@ -141,7 +136,7 @@ def handle_match(self, match): date_time = match.group('date_time') date_time, ms = date_time.split(',') date_time = DateTime.strptime(date_time, self.date_time_fmt) - ms = DateTimeDelta(0, 0, 0, old_div(int(ms), 1000.0)) + ms = DateTimeDelta(0, 0, 0, int(ms) // 1000.0) date_time = date_time + ms if message.startswith('LOADING_IMAGE'): name = message[message.find(':') + 2:] diff --git a/src/omero/util/metadata_mapannotations.py b/src/omero/util/metadata_mapannotations.py index d4c3cda5b..443c3112e 100644 --- a/src/omero/util/metadata_mapannotations.py +++ b/src/omero/util/metadata_mapannotations.py @@ -23,9 +23,6 @@ Utilities for manipulating map-annotations used as metadata """ -from builtins import str -from builtins import range -from builtins import object import logging from omero.model import NamedValue from omero.rtypes import rstring, unwrap diff --git a/src/omero/util/metadata_utils.py b/src/omero/util/metadata_utils.py index d22a7d6c3..6cee0da9d 100644 --- a/src/omero/util/metadata_utils.py +++ b/src/omero/util/metadata_utils.py @@ -26,9 +26,6 @@ data for clients. """ -from builtins import range -from past.builtins import basestring -from builtins import object from collections import deque, OrderedDict from omero.constants import namespaces import re @@ -391,7 +388,7 @@ def valuesub(v, cv): if cfg["omitempty"]: values = [v for v in values if v is not None and ( - not isinstance(v, basestring) or v.strip())] + not isinstance(v, str) or v.strip())] if cfg["clientvalue"] is not None: values = [valuesub(v, cfg["clientvalue"]) for v in values] diff --git a/src/omero/util/populate_metadata.py b/src/omero/util/populate_metadata.py index a97acd615..1dfda363d 100644 --- a/src/omero/util/populate_metadata.py +++ b/src/omero/util/populate_metadata.py @@ -3,8 +3,6 @@ """ Populate bulk metadata tables from delimited text files. """ -from __future__ import print_function -from __future__ import absolute_import # # Copyright (C) 2011-2014 University of Dundee. All rights reserved. @@ -25,13 +23,6 @@ # -from builtins import zip -from builtins import chr -from builtins import str -from builtins import range -from past.builtins import basestring -from future.utils import native_str -from builtins import object import logging import gzip import sys @@ -64,7 +55,7 @@ from omero.util import pydict_text_io from omero import client -from .populate_roi import ThreadPool +from omero.util.populate_roi import ThreadPool log = logging.getLogger("omero.util.populate_metadata") @@ -876,7 +867,7 @@ def populate(self, rows): values.append(value) try: log.debug("Value's class: %s" % value.__class__) - if isinstance(value, basestring): + if isinstance(value, str): column.size = max(column.size, len(value)) except TypeError: log.error('Original value "%s" now "%s" of bad type!' % ( @@ -997,7 +988,7 @@ def write_to_omero(self, batch_size=1000, loops=10, ms=500): sr = sf.sharedResources() update_service = sf.getUpdateService() name = 'bulk_annotations' - table = sr.newTable(1, name, {'omero.group': native_str(group)}) + table = sr.newTable(1, name, {'omero.group': str(group)}) if table is None: raise MetadataError( "Unable to create table: %s" % name) @@ -1035,7 +1026,7 @@ def write_to_omero(self, batch_size=1000, loops=10, ms=500): link = self.create_annotation_link() link.parent = self.target_object link.child = file_annotation - update_service.saveObject(link, {'omero.group': native_str(group)}) + update_service.saveObject(link, {'omero.group': str(group)}) class _QueryContext(object): @@ -1105,7 +1096,7 @@ def projection(self, q, ids, nss=None, batch_size=None): nids = 1 single_id = ids - if isinstance(nss, basestring): + if isinstance(nss, str): params.addString("ns", nss) elif nss: params.map['nss'] = rlist(rstring(s) for s in nss) @@ -1300,7 +1291,7 @@ def _save_annotation_links(self, links): group = str(self.target_object.details.group.id) update_service = sf.getUpdateService() arr = update_service.saveAndReturnArray( - links, {'omero.group': native_str(group)}) + links, {'omero.group': str(group)}) return arr def _save_annotation_and_links(self, links, ann, batch_size): @@ -1325,7 +1316,7 @@ def _save_annotation_and_links(self, links, ann, batch_size): for link in batch: link.setChild(annobj) update_service.saveArray( - batch, {'omero.group': native_str(group)}) + batch, {'omero.group': str(group)}) sz += len(batch) return sz diff --git a/src/omero/util/populate_roi.py b/src/omero/util/populate_roi.py index a193b8645..82ab62e69 100644 --- a/src/omero/util/populate_roi.py +++ b/src/omero/util/populate_roi.py @@ -3,8 +3,6 @@ """ ... """ -from __future__ import division -from __future__ import print_function # # Copyright (C) 2009 University of Dundee. All rights reserved. @@ -25,12 +23,6 @@ # -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import range -from past.utils import old_div -from builtins import object import tempfile import logging import time @@ -168,7 +160,7 @@ def get_original_file_data(self, original_file): temporary_file = tempfile.NamedTemporaryFile(mode='rt+', dir=str(self.dir)) size = original_file.size.val - for i in range((old_div(size, self.BUFFER_SIZE)) + 1): + for i in range((size // self.BUFFER_SIZE) + 1): index = i * self.BUFFER_SIZE data = self.raw_file_store.read(index, self.BUFFER_SIZE) temporary_file.write(data.decode("utf-8")) @@ -216,7 +208,7 @@ def guess_geometry(self, images): def colrow_from_wellnumber(self, width, wellnumber): x = wellnumber - 1 col = x % width - row = old_div(x, width) + row = x // width return (col, row) def image_from_wellnumber(self, wellnumber): diff --git a/src/omero/util/pydict_text_io.py b/src/omero/util/pydict_text_io.py index 9c40b8d1d..a89901e72 100644 --- a/src/omero/util/pydict_text_io.py +++ b/src/omero/util/pydict_text_io.py @@ -22,12 +22,10 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # -from past.builtins import basestring import os import json import re from omero.rtypes import unwrap -from future.utils import bytes_to_native_str import yaml @@ -49,7 +47,7 @@ def load(fileobj, filetype=None, single=True, session=None): :param session: If fileobj is an OriginalFile:ID a valid session is required """ - if not isinstance(fileobj, basestring): + if not isinstance(fileobj, (str, bytes)): raise Exception( 'Invalid type: fileobj must be a filename or json string') @@ -84,7 +82,7 @@ def load(fileobj, filetype=None, single=True, session=None): data = json.loads(rawdata) except TypeError: # for Python 3.5 - data = json.loads(bytes_to_native_str(rawdata)) + data = json.loads(rawdata.decode("utf-8")) if single: return data return [data] diff --git a/src/omero/util/roi_handling_utils.py b/src/omero/util/roi_handling_utils.py index 93aa5b82e..2e737eba8 100644 --- a/src/omero/util/roi_handling_utils.py +++ b/src/omero/util/roi_handling_utils.py @@ -21,10 +21,7 @@ """ Utility methods for manipulating roi. """ -from __future__ import division -from builtins import map -from past.utils import old_div from numpy import asarray, int32, zeros, hstack, vstack import omero.util.script_utils as script_utils import math @@ -56,8 +53,8 @@ def get_line_data(pixels, x1, y1, x2, y2, line_w=2, the_z=0, the_c=0, the_t=0): # How much extra Height do we need, top and bottom? extra_h = abs(math.sin(rads) * line_w) - bottom = int(max(y1, y2) + old_div(extra_h,2)) - top = int(min(y1, y2) - old_div(extra_h,2)) + bottom = int(max(y1, y2) + extra_h // 2) + top = int(min(y1, y2) - extra_h // 2) # How much extra width do we need, left and right? extra_w = abs(math.cos(rads) * line_w) @@ -120,9 +117,9 @@ def get_line_data(pixels, x1, y1, x2, y2, line_w=2, the_z=0, the_c=0, the_t=0): # finally we need to crop to the length of the line length = int(math.sqrt(math.pow(line_x, 2) + math.pow(line_y, 2))) rot_w, rot_h = rotated.size - crop_x = old_div((rot_w - length),2) + crop_x = (rot_w - length) // 2 crop_x2 = crop_x + length - crop_y = old_div((rot_h - line_w),2) + crop_y = (rot_h - line_w) // 2 crop_y2 = crop_y + line_w cropped = rotated.crop((crop_x, crop_y, crop_x2, crop_y2)) return asarray(cropped) diff --git a/src/omero/util/script_utils.py b/src/omero/util/script_utils.py index 07d390575..85c3d0811 100644 --- a/src/omero/util/script_utils.py +++ b/src/omero/util/script_utils.py @@ -21,13 +21,7 @@ """ Utility methods for dealing with scripts. """ -from __future__ import division -from future.utils import native_str -from builtins import hex -from builtins import str -from builtins import range -from past.utils import old_div import logging import os import warnings @@ -49,13 +43,7 @@ import sha hash_sha1 = sha.new -try: - from PIL import Image # see ticket:2597 -except: # pragma: nocover - try: - import Image # see ticket:2597 - except: - logging.error('No Pillow installed') +from PIL import Image # r,g,b,a colours for use in scripts. COLOURS = { @@ -674,7 +662,7 @@ def download_plane(raw_pixels_store, pixels, z, c, t): size_x = pixels.getSizeX().getValue() size_y = pixels.getSizeY().getValue() pixel_type = pixels.getPixelsType().getValue().getValue() - convert_type = '>' + native_str(size_x * size_y) + \ + convert_type = '>' + str(size_x * size_y) + \ pixelstypetopython.toPython(pixel_type) converted_plane = unpack(convert_type, raw_plane) numpy_type = pixelstypetopython.toNumpy(pixel_type) @@ -924,10 +912,7 @@ def split_image(client, imageId, dir, raw_pixels_store = session.createRawPixelsStore() pixels_service = session.getPixelsService() - try: - from PIL import Image # see ticket:2597 - except: - import Image # see ticket:2597 + from PIL import Image query_string = "select p from Pixels p join fetch p.image " \ "as i join fetch p.pixelsType where i.id='%s'" % imageId @@ -1566,7 +1551,7 @@ def convert_numpy_array(plane, min_max, type): val_range = max_val - min_val if (val_range == 0): val_range = 1 - scaled = (plane - min_val) * (old_div(float(255), val_range)) + scaled = (plane - min_val) * (255 / val_range) conv_array = zeros(plane.shape, dtype=type) try: conv_array += scaled diff --git a/src/omero/util/sessions.py b/src/omero/util/sessions.py index a42415886..d84170035 100644 --- a/src/omero/util/sessions.py +++ b/src/omero/util/sessions.py @@ -22,24 +22,13 @@ """ Library for managing user sessions. """ -from __future__ import division -from __future__ import print_function - -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import object -from past.utils import old_div + import omero.constants from omero.util import get_omero_userdir, make_logname from omero.rtypes import rlong from omero_ext.path import path -try: - from urllib.parse import quote, unquote -except ImportError: - # Python2 - from urllib.parse import quote, unquote +from urllib.parse import quote, unquote import logging @@ -80,7 +69,7 @@ def __init__(self, dir=None): """ self.logger = logging.getLogger(make_logname(self)) if dir is None: - self.dir = old_div(get_omero_userdir(), "sessions") + self.dir = get_omero_userdir() / "sessions" else: self.dir = path(dir) if not self.dir.exists(): @@ -125,7 +114,7 @@ def add(self, host, name, id, props, sudo=None): if not dhn.exists(): dhn.makedirs() - (old_div(dhn, id)).write_lines(lines) + (dhn / id).write_lines(lines) def conflicts(self, host, name, id, new_props, ignore_nulls=False, check_group=True): @@ -168,7 +157,7 @@ def remove(self, host, name, uuid): return d = self.dir / _escape_host(host) / name if d.exists(): - f = old_div(d, uuid) + f = d / uuid if f.exists(): f.remove() self.logger.debug("Removed %s" % f) @@ -183,7 +172,7 @@ def exists(self, host, name, uuid): """ d = self.dir for x in (_escape_host(host), name, uuid): - d = old_div(d, x) + d = d / x if not d.exists(): return False return True @@ -273,11 +262,11 @@ def find_name_by_key(self, server, uuid): name since keys should be UUIDs. A None may be returned. """ - s = old_div(self.dir, server) + s = self.dir / server if not s.exists(): return None else: - n = [x.basename() for x in s.dirs() if (old_div(x, uuid)).exists()] + n = [x.basename() for x in s.dirs() if (x / uuid).exists()] if not n: return None elif len(n) == 1: @@ -449,25 +438,25 @@ def f(h, n, s): def host_file(self): """ Returns the path-object which stores the last active host """ - return old_div(self.dir, "._LASTHOST_") + return self.dir / "._LASTHOST_" def port_file(self): """ Returns the path-object which stores the last active port """ - return old_div(self.dir, "._LASTPORT_") + return self.dir / "._LASTPORT_" def user_file(self, host): """ Returns the path-object which stores the last active user """ - d = old_div(self.dir, _escape_host(host)) + d = self.dir / _escape_host(host) if not d.exists(): d.makedirs() - return old_div(d, "._LASTUSER_") + return d / "._LASTUSER_" def sess_file(self, host, user): """ Returns the path-object which stores the last active session """ d = self.dir / _escape_host(host) / user if not d.exists(): d.makedirs() - return old_div(d, "._LASTSESS_") + return d / "._LASTSESS_" def non_dot(self, d): """ diff --git a/src/omero/util/temp_files.py b/src/omero/util/temp_files.py index f8d5226f9..efde0313f 100644 --- a/src/omero/util/temp_files.py +++ b/src/omero/util/temp_files.py @@ -7,13 +7,7 @@ """ OMERO Support for temporary files and directories """ -from __future__ import division -from __future__ import print_function -from builtins import input -from builtins import str -from builtins import object -from past.utils import old_div import os import sys import atexit @@ -55,8 +49,8 @@ def __init__(self, prefix="omero"): self.is_win32 = (sys.platform == "win32") self.prefix = prefix - self.userdir = old_div(self.tmpdir(), ("%s_%s" % - (self.prefix, self.username()))) + self.userdir = self.tmpdir() / ("%s_%s" % + (self.prefix, self.username())) """ User-accessible directory of the form $TMPDIR/omero_$USERNAME. If the given directory is not writable, an attempt is made @@ -71,7 +65,7 @@ def __init__(self, prefix="omero"): break raise Exception( "Failed to create temporary directory: %s" % self.userdir) - self.dir = old_div(self.userdir, self.pid()) + self.dir = self.userdir / self.pid() """ Directory under which all temporary files and folders will be created. An attempt to remove a path not in this directory will lead to an @@ -86,7 +80,7 @@ def __init__(self, prefix="omero"): self.lock = None try: - self.lock = open(str(old_div(self.dir, ".lock")), "a+") + self.lock = open(str(self.dir / ".lock"), "a+") """ .lock file under self.dir which is used to prevent other TempFileManager instances (also in other languages) from @@ -155,7 +149,7 @@ def tmpdir(self): targets = [] if custom_tmpdir: targets.append(path(custom_tmpdir)) - targets.append(old_div(get_omero_userdir(), "tmp")) + targets.append(get_omero_userdir() / "tmp") targets.append(path(tempfile.gettempdir()) / "omero" / "tmp") # Handles existing files named tmp @@ -328,7 +322,7 @@ def clean_userdir(self): if str(dir) == str(self.dir): self.logger.debug("Skipping self: %s", dir) continue - lock = old_div(dir, ".lock") + lock = dir / ".lock" if lock.exists(): # 1962, on Windows this fails if lock is missing f = open(str(lock), "r") try: diff --git a/src/omero/util/text.py b/src/omero/util/text.py index 4832fcf29..249c8ca81 100644 --- a/src/omero/util/text.py +++ b/src/omero/util/text.py @@ -11,15 +11,6 @@ # The following classes (ALIGN, Column, Table) were originally from # http://code.activestate.com/recipes/577202-render-tables-for-text-interface/ # -from __future__ import unicode_literals -from __future__ import division -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import zip -from builtins import range -from past.utils import old_div -from builtins import object import json import os import sys @@ -79,21 +70,11 @@ def _write_row(self, table, i): try: import csv import io - if sys.version_info >= (3, 0, 0): - output = io.StringIO() - def _encode(s): - return s - def _decode(s): - return s - else: - # Python 2.7 csv module does not support unicode! - # https://docs.python.org/2.7/library/csv.html#module-csv - # Need to treat as bytes and encode/decode - output = io.BytesIO() - def _encode(s): - return s.encode('utf-8') - def _decode(s): - return s.decode('utf-8') + output = io.StringIO() + def _encode(s): + return s + def _decode(s): + return s writer = csv.writer(output, lineterminator='') writer.writerow([_encode(s) for s in table.get_row(i)]) return _decode(output.getvalue()) @@ -309,19 +290,11 @@ class ALIGN(object): class Column(list): def __init__(self, name, data, align=ALIGN.LEFT, style=SQLStyle()): - if sys.version_info >= (3, 0, 0): - def tostring(x): - if isinstance(x, bytes): - return x.decode("utf-8", "surrogateescape") - else: - return str(x) - else: - def tostring(x): - try: - return str(x) - except UnicodeDecodeError: - # Unicode characters are present - return str(x.decode("utf-8", "ignore")) + def tostring(x): + if isinstance(x, bytes): + return x.decode("utf-8", "surrogateescape") + else: + return str(x) decoded = [tostring(d) for d in data] list.__init__(self, decoded) @@ -349,33 +322,18 @@ def get_row(self, i=None): if i is None: yield x.format % x.name else: - if sys.version_info >= (3, 0, 0): - if isinstance(x[i], bytes): - yield x.format % bytes.decode( - "utf-8", "surrogateescape") - else: - yield x.format % str(x[i]) + if isinstance(x[i], bytes): + yield x.format % bytes.decode( + "utf-8", "surrogateescape") else: - try: - yield x.format % x[i].decode("ascii") - except UnicodeEncodeError: - yield x.format % x[i] - except UnicodeDecodeError: # Unicode characters are present - yield (x.format % x[i].decode("utf-8")).encode("utf-8") - except AttributeError: # Unicode characters are present - yield x.format % x[i] - else: - yield x.format % x[i] + yield x.format % str(x[i]) def get_rows(self): for row in self.style.get_rows(self): yield row def __str__(self): - if sys.version_info >= (3, 0, 0): - return '\n'.join(self.get_rows()) - else: - return ('\n'.join(self.get_rows())).encode("utf-8") + return '\n'.join(self.get_rows()) def filesizeformat(bytes): @@ -401,14 +359,14 @@ def filesizeformat(bytes): if bytes < KB: value = "%(size)d B" % {'size': bytes} elif bytes < MB: - value = "%s KB" % filesize_number_format(old_div(bytes, KB)) + value = "%s KB" % filesize_number_format(bytes // KB) elif bytes < GB: - value = "%s MB" % filesize_number_format(old_div(bytes, MB)) + value = "%s MB" % filesize_number_format(bytes // MB) elif bytes < TB: - value = "%s GB" % filesize_number_format(old_div(bytes, GB)) + value = "%s GB" % filesize_number_format(bytes // GB) elif bytes < PB: - value = "%s TB" % filesize_number_format(old_div(bytes, TB)) + value = "%s TB" % filesize_number_format(bytes // TB) else: - value = "%s PB" % filesize_number_format(old_div(bytes, PB)) + value = "%s PB" % filesize_number_format(bytes // PB) return value diff --git a/src/omero/util/tiles.py b/src/omero/util/tiles.py index 4355f17a9..b2dd09d0e 100644 --- a/src/omero/util/tiles.py +++ b/src/omero/util/tiles.py @@ -4,12 +4,6 @@ # Copyright 2011 Glencoe Software, Inc. All rights reserved. # Use is subject to license terms supplied in LICENSE.txt -from __future__ import division - - -from builtins import range -from past.utils import old_div -from builtins import object class TileLoopIteration(object): """ "Interface" which must be passed to forEachTile @@ -95,10 +89,10 @@ def forEachTile(self, sizeX, sizeY, sizeZ, sizeC, sizeT, for z in range(0, sizeZ): for tileOffsetY in range( - 0, (old_div((sizeY + tileHeight - 1), tileHeight))): + 0, ((sizeY + tileHeight - 1) // tileHeight)): for tileOffsetX in range( - 0, (old_div((sizeX + tileWidth - 1), tileWidth))): + 0, ((sizeX + tileWidth - 1) // tileWidth)): x = tileOffsetX * tileWidth y = tileOffsetY * tileHeight diff --git a/src/omero/util/upgrade_check.py b/src/omero/util/upgrade_check.py index fd0ccc346..356c2f118 100644 --- a/src/omero/util/upgrade_check.py +++ b/src/omero/util/upgrade_check.py @@ -5,15 +5,11 @@ # Copyright 2009 Glencoe Software, Inc. All rights reserved. # Use is subject to license terms supplied in LICENSE.txt -from future import standard_library -from builtins import str -from builtins import object from omero_version import omero_version import platform import logging import requests -standard_library.install_aliases() # Ensure we are using pyopenssl (ome/omero-py#240) try: diff --git a/src/omero_ext/argparse.py b/src/omero_ext/argparse.py index 1718fadaf..eff508409 100644 --- a/src/omero_ext/argparse.py +++ b/src/omero_ext/argparse.py @@ -76,12 +76,6 @@ still considered an implementation detail.) """ -from builtins import zip -from builtins import map -from builtins import str -from builtins import range -from past.builtins import basestring -from builtins import object __version__ = '1.1' __all__ = [ 'ArgumentParser', @@ -109,11 +103,6 @@ except NameError: from sets import Set as _set -try: - _basestring = basestring -except NameError: - _basestring = str - try: _sorted = sorted except NameError: @@ -129,15 +118,6 @@ def _sorted(iterable, reverse=False): def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') -# silence Python 2.6 buggy warnings about Exception.message -if _sys.version_info[:2] == (2, 6): - import warnings - warnings.filterwarnings( - action='ignore', - message='BaseException.message has been deprecated as of Python 2.6', - category=DeprecationWarning, - module='omero_ext.argparse') - SUPPRESS = '==SUPPRESS==' @@ -1726,7 +1706,7 @@ def parse_known_args(self, args=None, namespace=None): if not hasattr(namespace, action.dest): if action.default is not SUPPRESS: default = action.default - if isinstance(action.default, _basestring): + if isinstance(action.default, str): default = self._get_value(action, default) setattr(namespace, action.dest, default) @@ -2200,7 +2180,7 @@ def _get_values(self, action, arg_strings): value = action.const else: value = action.default - if isinstance(value, _basestring): + if isinstance(value, str): value = self._get_value(action, value) self._check_value(action, value) diff --git a/src/omero_ext/killableprocess.py b/src/omero_ext/killableprocess.py index 20c80f271..0a6ff108f 100644 --- a/src/omero_ext/killableprocess.py +++ b/src/omero_ext/killableprocess.py @@ -47,7 +47,6 @@ Note: On Windows, this module requires Windows 2000 or higher (no support for Windows 95, 98, or NT 4.0). """ -from __future__ import absolute_import import subprocess import sys diff --git a/src/omero_ext/path.py b/src/omero_ext/path.py index 6543f3a99..e202d06ac 100644 --- a/src/omero_ext/path.py +++ b/src/omero_ext/path.py @@ -20,8 +20,6 @@ # SOFTWARE. # -from __future__ import division -from __future__ import with_statement """ path.py - An object representing a path to a file or directory. @@ -43,15 +41,6 @@ * Added parpath (2009/09/21) """ -from builtins import zip -from builtins import chr -from builtins import map -from builtins import str -from past.builtins import basestring -from past.utils import old_div -from builtins import bytes -from builtins import object - import sys import warnings import os @@ -72,67 +61,19 @@ except ImportError: pass -try: - import pwd -except ImportError: - pass +import pwd +from functools import reduce -################################ -# Monkey patchy python 3 support -try: - basestring -except NameError: - basestring = str +getcwdu = os.getcwd -try: - str -except NameError: - str = str - -try: - getcwdu = os.getcwd -except AttributeError: - getcwdu = os.getcwd - -PY3 = sys.version_info[0] >= 3 -if PY3: - def u(x): - return x -else: - def u(x): - return codecs.unicode_escape_decode(x)[0] +def u(x): + return x o777 = 511 o766 = 502 o666 = 438 o554 = 364 -################################ - -########################## -# Python 2.5 compatibility -try: - from functools import reduce -except ImportError: - pass -########################## -############################################################## -# Support for surrogateescape - - -def surrogate_escape(error): - """ - Simulate the Python 3 surrogateescape handler, but for Python 2 only. - """ - chars = error.object[error.start:error.end] - assert len(chars) == 1 - val = ord(chars) - val += 0xdc00 - return chr(val), error.end - -if not PY3: - codecs.register_error('surrogateescape', surrogate_escape) -############################################################### __version__ = '5.2' __all__ = ['path', 'CaseInsensitivePattern'] @@ -216,9 +157,7 @@ def _always_unicode(cls, path): Ensure the path as retrieved from a Python API, such as os.listdir, is a proper Unicode string. """ - if PY3 or isinstance(path, str): - return path - return path.decode(sys.getfilesystemencoding(), 'surrogateescape') + return path # --- Special Python methods. @@ -233,7 +172,7 @@ def __add__(self, more): return NotImplemented def __radd__(self, other): - if not isinstance(other, basestring): + if not isinstance(other, str): return NotImplemented return self._next_class(other.__add__(self)) @@ -543,7 +482,7 @@ def listdir(self, pattern=None, unreadable_as_empty=False): if pattern is None: pattern = '*' return [ - old_div(self, child) + self / child for child in map(self._always_unicode, names) if self._next_class(child).fnmatch(pattern) ] @@ -741,7 +680,7 @@ def glob(self, pattern): .. seealso:: :func:`glob.glob` """ cls = self._next_class - return [cls(s) for s in glob.glob(old_div(self, pattern))] + return [cls(s) for s in glob.glob(self / pattern)] # # --- Reading or writing an entire file at once. @@ -1376,7 +1315,7 @@ def readlinkabs(self): if p.isabs(): return p else: - return (old_div(self.parent, p)).abspath() + return (self.parent / p).abspath() # # --- High-level functions from shutil diff --git a/src/omero_ext/pyinotify.py b/src/omero_ext/pyinotify.py index 6eb0dad82..00fb4e9b1 100755 --- a/src/omero_ext/pyinotify.py +++ b/src/omero_ext/pyinotify.py @@ -28,15 +28,7 @@ @license: MIT License @contact: seb@dbzteam.org """ -from __future__ import division -from __future__ import print_function - -from builtins import map -from builtins import hex -from builtins import str -from past.builtins import basestring -from past.utils import old_div -from builtins import object + class PyinotifyError(Exception): """Indicates exceptions raised by a Pyinotify class.""" pass @@ -68,8 +60,6 @@ def __init__(self): # Check Python version import sys -if sys.version < '2.4': - raise UnsupportedPythonVersionError(sys.version) # Import directives @@ -93,10 +83,7 @@ def __init__(self): import asyncore import glob -try: - from functools import reduce -except ImportError: - pass # Will fail on Python 2.4 which has reduce() builtin anyway. +from functools import reduce __author__ = "seb@dbzteam.org (Sebastien Martini)" @@ -125,15 +112,11 @@ def load_libc(): except (OSError, IOError): pass # Will attemp to load it with None anyway. - if sys.version_info[0] >= 2 and sys.version_info[1] >= 6: - LIBC = ctypes.CDLL(libc, use_errno=True) - def _strerrno(): - code = ctypes.get_errno() - return ' Errno=%s (%s)' % (os.strerror(code), errno.errorcode[code]) - strerrno = _strerrno - else: - LIBC = ctypes.CDLL(libc) - strerrno = lambda : '' + LIBC = ctypes.CDLL(libc, use_errno=True) + def _strerrno(): + code = ctypes.get_errno() + return ' Errno=%s (%s)' % (os.strerror(code), errno.errorcode[code]) + strerrno = _strerrno # Check that libc has needed functions inside. if (not hasattr(LIBC, 'inotify_init') or @@ -163,14 +146,8 @@ def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, class UnicodeLogRecord(logging.LogRecord): def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None): - py_version = sys.version_info - # func argument was added in Python 2.5, just ignore it otherwise. - if py_version[0] >= 2 and py_version[1] >= 5: - logging.LogRecord.__init__(self, name, level, pathname, lineno, - msg, args, exc_info, func) - else: - logging.LogRecord.__init__(self, name, level, pathname, lineno, - msg, args, exc_info) + logging.LogRecord.__init__(self, name, level, pathname, lineno, + msg, args, exc_info, func) def getMessage(self): msg = self.msg @@ -437,7 +414,7 @@ def __repr__(self): continue if attr == 'mask': value = hex(getattr(self, attr)) - elif isinstance(value, basestring) and not value: + elif isinstance(value, str) and not value: value = "''" s += ' %s%s%s' % (output_format.field_name(attr), output_format.punctuation('='), @@ -963,11 +940,11 @@ def __repr__(self): if elapsed < 60: elapsed_str = str(elapsed) + 'sec' elif 60 <= elapsed < 3600: - elapsed_str = '%dmn%dsec' % (old_div(elapsed, 60), elapsed % 60) + elapsed_str = '%dmn%dsec' % (elapsed // 60, elapsed % 60) elif 3600 <= elapsed < 86400: - elapsed_str = '%dh%dmn' % (old_div(elapsed, 3600), old_div((elapsed % 3600), 60)) + elapsed_str = '%dh%dmn' % (elapsed // 3600, (elapsed % 3600) // 60) elif elapsed >= 86400: - elapsed_str = '%dd%dh' % (old_div(elapsed, 86400), old_div((elapsed % 86400), 3600)) + elapsed_str = '%dd%dh' % (elapsed // 86400, (elapsed % 86400) // 3600) stats['ElapsedTime'] = elapsed_str l = [] @@ -997,7 +974,7 @@ def __str__(self, scale=45): return '' m = max(stats.values()) - unity = old_div(float(scale), m) + unity = scale / m fmt = '%%-26s%%-%ds%%s' % (len(output_format.field_value('@' * scale)) + 1) def func(x): diff --git a/src/omero_ext/stubout.py b/src/omero_ext/stubout.py index 38a8ced48..a47921427 100644 --- a/src/omero_ext/stubout.py +++ b/src/omero_ext/stubout.py @@ -15,7 +15,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from builtins import object import inspect diff --git a/src/omero_ext/which.py b/src/omero_ext/which.py index 5dc25b5f5..4a35800e8 100644 --- a/src/omero_ext/which.py +++ b/src/omero_ext/which.py @@ -33,12 +33,7 @@ from PATH element 0 from HKLM\SOFTWARE\...\perl.exe """ -from __future__ import print_function -from future import standard_library -standard_library.install_aliases() -from builtins import map -from builtins import range _cmdlnUsage = """ Show the full path of commands. diff --git a/src/omero_ext/winprocess.py b/src/omero_ext/winprocess.py index 3be253f3b..bf95ccd7c 100644 --- a/src/omero_ext/winprocess.py +++ b/src/omero_ext/winprocess.py @@ -29,7 +29,6 @@ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -from builtins import object from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LPCWSTR, LPWSTR, UINT, WORD diff --git a/src/omero_model_ElectricPotentialI.py b/src/omero_model_ElectricPotentialI.py index 95e874bde..c1b68a214 100644 --- a/src/omero_model_ElectricPotentialI.py +++ b/src/omero_model_ElectricPotentialI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_ElectricPotential_ice") @@ -923,7 +921,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsElectricPotential): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsElectricPotential, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_FrequencyI.py b/src/omero_model_FrequencyI.py index af87945f5..ddf35cd76 100644 --- a/src/omero_model_FrequencyI.py +++ b/src/omero_model_FrequencyI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Frequency_ice") @@ -923,7 +921,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsFrequency): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsFrequency, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_LengthI.py b/src/omero_model_LengthI.py index a2b9c272c..f1aa986ff 100644 --- a/src/omero_model_LengthI.py +++ b/src/omero_model_LengthI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Length_ice") @@ -2080,7 +2078,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsLength): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsLength, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_PowerI.py b/src/omero_model_PowerI.py index ceca59576..447bd6cb2 100644 --- a/src/omero_model_PowerI.py +++ b/src/omero_model_PowerI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Power_ice") @@ -923,7 +921,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsPower): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsPower, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_PressureI.py b/src/omero_model_PressureI.py index af6725225..e8f8092ec 100644 --- a/src/omero_model_PressureI.py +++ b/src/omero_model_PressureI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Pressure_ice") @@ -2078,7 +2076,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsPressure): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsPressure, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_TemperatureI.py b/src/omero_model_TemperatureI.py index 6855b774f..b30c0a116 100644 --- a/src/omero_model_TemperatureI.py +++ b/src/omero_model_TemperatureI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Temperature_ice") @@ -90,7 +88,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsTemperature): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsTemperature, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_TimeI.py b/src/omero_model_TimeI.py index e3c079be9..d0a2cee2f 100644 --- a/src/omero_model_TimeI.py +++ b/src/omero_model_TimeI.py @@ -25,8 +25,6 @@ """ -from builtins import str -from past.builtins import basestring import Ice import IceImport IceImport.load("omero_model_Time_ice") @@ -1190,7 +1188,7 @@ def __init__(self, value=None, unit=None): target = None elif isinstance(unit, UnitsTime): target = unit - elif isinstance(unit, basestring): + elif isinstance(unit, str): target = getattr(UnitsTime, unit) else: raise Exception("Unknown unit: %s (%s)" % ( diff --git a/src/omero_model_UnitBase.py b/src/omero_model_UnitBase.py index e69d0fdcb..f1f2acf51 100644 --- a/src/omero_model_UnitBase.py +++ b/src/omero_model_UnitBase.py @@ -25,8 +25,6 @@ """ -from builtins import str -from builtins import object class UnitBase(object): def _base_string(self, v, u): diff --git a/test.sh b/test.sh deleted file mode 100755 index d1328c986..000000000 --- a/test.sh +++ /dev/null @@ -1,9 +0,0 @@ -set -e -set -u -set -x -IMAGE=${IMAGE:-${USER}-py-test} -PIP_CACHE_DIR=${PIP_CACHE_DIR:-/tmp/pip-cache} -mkdir -m 777 -p ${PIP_CACHE_DIR} -chmod a+t ${PIP_CACHE_DIR} -docker build -t ${IMAGE} . -docker run -ti --rm -v ${PIP_CACHE_DIR}:/tmp/pip-cache ${IMAGE} "$@" diff --git a/test/conftest.py b/test/conftest.py index e24487220..f8e393f8a 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -5,8 +5,6 @@ # how-can-i-repeat-each-test-multiple-times-in-a-py-test-run # -from builtins import range -from builtins import object import os import pytest diff --git a/test/unit/clitest/test_admin.py b/test/unit/clitest/test_admin.py index bab216b23..17cacc029 100644 --- a/test/unit/clitest/test_admin.py +++ b/test/unit/clitest/test_admin.py @@ -8,15 +8,11 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division - -from builtins import object import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) - from past.utils import old_div import os import re @@ -34,7 +30,7 @@ from omero_ext.path import path from omero_version import ice_compatibility -omeroDir = old_div(path(os.getcwd()), "build") +omeroDir = path(os.getcwd()) / "build" GRID_FILES = ["templates.xml", "default.xml", "windefault.xml"] ETC_FILES = ["ice.config", "master.cfg", "internal.cfg"] @@ -68,7 +64,7 @@ def tmpadmindir(tmpdir, monkeypatch): for f in glob(os.path.join(old_templates_dir, "*.cfg")): path(f).copy(path(templates_dir)) for f in glob(os.path.join(old_templates_dir, "grid", "*.xml")): - path(f).copy(path(old_div(templates_dir, "grid"))) + path(f).copy(path(templates_dir / "grid")) path(os.path.join(old_templates_dir, "ice.config")).copy(path(templates_dir)) # The OMERODIR env-var is directly reference in other omero components so # we need to override it @@ -366,7 +362,7 @@ def check_default_xml(topdir, prefix='', tcp=4063, ssl=4064, ws=4065, wss=4066, client_endpoints = 'client-endpoints="%s"' % ':'.join(client_endpoint_list) for key in ['default.xml', 'windefault.xml']: - s = path(old_div(topdir, "etc" / "grid" / key)).text() + s = path(topdir / "etc" / "grid" / key).text() assert routerport in s assert insecure_routerport in s assert client_endpoints in s diff --git a/test/unit/clitest/test_basics.py b/test/unit/clitest/test_basics.py index 538c3dc64..32b4e470a 100644 --- a/test/unit/clitest/test_basics.py +++ b/test/unit/clitest/test_basics.py @@ -20,8 +20,6 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from __future__ import unicode_literals -from builtins import object import pytest from omero.cli import CLI diff --git a/test/unit/clitest/test_chgrp.py b/test/unit/clitest/test_chgrp.py index ff5ba400e..62166a712 100644 --- a/test/unit/clitest/test_chgrp.py +++ b/test/unit/clitest/test_chgrp.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object from omero.cli import CLI from omero.plugins.chgrp import ChgrpControl diff --git a/test/unit/clitest/test_cli.py b/test/unit/clitest/test_cli.py index 1fb62d893..41e24dbc3 100644 --- a/test/unit/clitest/test_cli.py +++ b/test/unit/clitest/test_cli.py @@ -9,8 +9,6 @@ """ -from builtins import range -from builtins import object import pytest from omero.cli import CLI, NonZeroReturnCode diff --git a/test/unit/clitest/test_db.py b/test/unit/clitest/test_db.py index 34666aa42..3e96b1265 100644 --- a/test/unit/clitest/test_db.py +++ b/test/unit/clitest/test_db.py @@ -9,10 +9,6 @@ """ -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import object import pytest import os from omero_ext.path import path @@ -21,7 +17,6 @@ from omero.cli import NonZeroReturnCode from omero.cli import CLI import getpass -import builtins OMERODIR = False if 'OMERODIR' in os.environ: diff --git a/test/unit/clitest/test_download.py b/test/unit/clitest/test_download.py index 172e5921c..bd6dfef3d 100644 --- a/test/unit/clitest/test_download.py +++ b/test/unit/clitest/test_download.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest from omero.plugins.download import DownloadControl from omero.cli import CLI, NonZeroReturnCode diff --git a/test/unit/clitest/test_export.py b/test/unit/clitest/test_export.py index c6ef6a44f..3748f8125 100644 --- a/test/unit/clitest/test_export.py +++ b/test/unit/clitest/test_export.py @@ -8,17 +8,14 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from builtins import object -from past.utils import old_div import os from omero_ext.path import path from omero.cli import CLI, NonZeroReturnCode from omero.plugins.export import ExportControl from omero.util.temp_files import create_path -omeroDir = old_div(path(os.getcwd()), "build") +omeroDir = path(os.getcwd()) / "build" class MockCLI(CLI): diff --git a/test/unit/clitest/test_fs.py b/test/unit/clitest/test_fs.py index eaf482d75..7b50f9e9c 100644 --- a/test/unit/clitest/test_fs.py +++ b/test/unit/clitest/test_fs.py @@ -20,7 +20,6 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest from omero.cli import CLI from omero.plugins.fs import FsControl diff --git a/test/unit/clitest/test_group.py b/test/unit/clitest/test_group.py index 40328dbba..b7772c246 100644 --- a/test/unit/clitest/test_group.py +++ b/test/unit/clitest/test_group.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest from omero.plugins.group import GroupControl from omero.cli import CLI diff --git a/test/unit/clitest/test_hql.py b/test/unit/clitest/test_hql.py index de3f40dac..e51dd5a31 100644 --- a/test/unit/clitest/test_hql.py +++ b/test/unit/clitest/test_hql.py @@ -20,7 +20,6 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest from omero.cli import CLI from omero.plugins.hql import HqlControl, BLACKLISTED_KEYS, WHITELISTED_VALUES diff --git a/test/unit/clitest/test_import.py b/test/unit/clitest/test_import.py index 51992b447..c42533211 100644 --- a/test/unit/clitest/test_import.py +++ b/test/unit/clitest/test_import.py @@ -8,15 +8,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from __future__ import print_function - -from future import standard_library -standard_library.install_aliases() -from builtins import str -from builtins import range -from builtins import object -from past.utils import old_div + import os import pytest import sys @@ -84,10 +76,10 @@ def add_client_dir(self): self.args += ["--logback", logback] def mkdir(self, parent, name, with_ds_store=False): - child = old_div(parent, name) + child = parent / name child.mkdir() if with_ds_store: - ds_store = old_div(child, ".DS_STORE") + ds_store = child / ".DS_STORE" ds_store.write("") return child @@ -108,8 +100,8 @@ def mkfakescreen(self, screen_dir, nplates=2, nruns=2, nwells=2, run_dir, "WellA00%s" % str(iwell), with_ds_store=with_ds_store) for ifield in range(nfields): - fieldfile = (old_div(well_dir, ("Field00%s.fake" % - str(ifield)))) + fieldfile = (well_dir / ("Field00%s.fake" % + str(ifield))) fieldfile.write('') fieldfiles.append(fieldfile) return fieldfiles @@ -121,12 +113,12 @@ def mkfakepattern(self, tmpdir, nangles=7, ntimepoints=10): tiffiles = [] for angle in range(1, nangles + 1): for timepoint in range(1, ntimepoints + 1): - tiffile = (old_div(spim_dir, ("spim_TL%s_Angle%s.fake" % - (str(timepoint), str(angle))))) + tiffile = (spim_dir / ("spim_TL%s_Angle%s.fake" % + (str(timepoint), str(angle)))) tiffile.write('') print(str(tiffile)) tiffiles.append(tiffile) - patternfile = old_div(spim_dir, "spim.pattern") + patternfile = spim_dir / "spim.pattern" patternfile.write("spim_TL<1-%s>_Angle<1-%s>.fake" % (str(ntimepoints), str(nangles))) assert len(tiffiles) == nangles * ntimepoints @@ -176,9 +168,9 @@ def testImportDepth(self, tmpdir, capfd, data): dir1 = tmpdir.join("a") dir1.mkdir() - dir2 = old_div(dir1, "b") + dir2 = dir1 / "b" dir2.mkdir() - fakefile = old_div(dir2, "test.fake") + fakefile = dir2 / "test.fake" fakefile.write('') self.add_client_dir() @@ -304,7 +296,7 @@ def new_client(x): c.setSessionId(sessionid) return c monkeypatch.setattr(self.cli, 'conn', new_client) - ice_config = old_div(tmpdir, 'ice.config') + ice_config = tmpdir / 'ice.config' ice_config.write('omero.host=%s\nomero.port=%g' % ( hostname, (port or 4064))) monkeypatch.setenv("ICE_CONFIG", "%s" % ice_config) @@ -381,7 +373,7 @@ def testYamlOutput(self, tmpdir, capfd): def testBulkNoPaths(self): t = path(__file__) / "bulk_import" / "test_simple" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" self.add_client_dir() self.args += ["-f", "---bulk=%s" % b, "dne.fake"] with pytest.raises(NonZeroReturnCode): @@ -389,7 +381,7 @@ def testBulkNoPaths(self): def testBulkSimple(self): t = path(__file__).parent / "bulk_import" / "test_simple" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" self.add_client_dir() self.args += ["-f", "---bulk=%s" % b] @@ -397,7 +389,7 @@ def testBulkSimple(self): def testBulkInclude(self): t = path(__file__).parent / "bulk_import" / "test_include" / "inner" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" self.add_client_dir() self.args += ["-f", "---bulk=%s" % b] @@ -407,7 +399,7 @@ def testBulkName(self): # Metadata provided in the yml file will be applied # to the args t = path(__file__).parent / "bulk_import" / "test_name" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" class MockImportControl(ImportControl): def do_import(self, command_args, xargs, mode): @@ -422,7 +414,7 @@ def testBulkCols(self): # Metadata provided about the individual columns in # the tsv will be used. t = path(__file__).parent / "bulk_import" / "test_cols" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" class MockImportControl(ImportControl): def do_import(self, command_args, xargs, mode): @@ -438,7 +430,7 @@ def do_import(self, command_args, xargs, mode): def testBulkBad(self): t = path(__file__).parent / "bulk_import" / "test_bad" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" self.add_client_dir() self.args += ["-f", "---bulk=%s" % b] @@ -447,7 +439,7 @@ def testBulkBad(self): def testBulkDry(self, capfd): t = path(__file__).parent / "bulk_import" / "test_dryrun" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" self.add_client_dir() self.args += ["-f", "---bulk=%s" % b] @@ -458,7 +450,7 @@ def testBulkDry(self, capfd): def testBulkJavaArgs(self): """Test Java arguments""" t = path(__file__).parent / "bulk_import" / "test_javaargs" - b = old_div(t, "bulk.yml") + b = t / "bulk.yml" class MockImportControl(ImportControl): def do_import(self, command_args, xargs, mode): @@ -511,13 +503,13 @@ def testImportCandidates(self, tmpdir): def testImportCandidatesDepth(self, tmpdir): dir1 = tmpdir.join("a") dir1.mkdir() - dir2 = old_div(dir1, "b") + dir2 = dir1 / "b" dir2.mkdir() - dir3 = old_div(dir2, "c") + dir3 = dir2 / "c" dir3.mkdir() - fakefile = old_div(dir2, "test.fake") + fakefile = dir2 / "test.fake" fakefile.write("") - fakefile2 = old_div(dir3, "test2.fake") + fakefile2 = dir3 / "test2.fake" fakefile2.write("") candidates = import_candidates.as_dictionary( str(tmpdir), extra_args=["--debug", "WARN", "--depth", "3"] diff --git a/test/unit/clitest/test_ldap.py b/test/unit/clitest/test_ldap.py index 718af9fd8..b05dd1b09 100644 --- a/test/unit/clitest/test_ldap.py +++ b/test/unit/clitest/test_ldap.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object from omero.cli import CLI from omero.plugins.ldap import LdapControl import pytest diff --git a/test/unit/clitest/test_obj.py b/test/unit/clitest/test_obj.py index eaf9520af..f4bfb767b 100644 --- a/test/unit/clitest/test_obj.py +++ b/test/unit/clitest/test_obj.py @@ -23,7 +23,6 @@ Test of the omero/plugins/tx.py module """ -from builtins import object import pytest from omero.cli import CLI from omero.model import ProjectI diff --git a/test/unit/clitest/test_prefs.py b/test/unit/clitest/test_prefs.py index 6b81b338e..4f727a954 100644 --- a/test/unit/clitest/test_prefs.py +++ b/test/unit/clitest/test_prefs.py @@ -1,8 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import unicode_literals - """ Test of the scripts plugin @@ -11,9 +9,6 @@ """ -from builtins import str -from past.builtins import basestring -from builtins import object import pytest import sys from omero.cli import CLI, NonZeroReturnCode @@ -23,11 +18,6 @@ from omero.util.temp_files import create_path -try: - basestring -except: - basestring = str - @pytest.fixture def configxml(monkeypatch): class MockConfigXml(object): @@ -62,7 +52,7 @@ def assertStdoutStderr(self, capsys, out='', err='', strip_warning=False): e.strip() == err) def invoke(self, s): - if isinstance(s, basestring): + if isinstance(s, str): s = s.split() self.cli.invoke(self.args + s, strict=True) diff --git a/test/unit/clitest/test_rcode.py b/test/unit/clitest/test_rcode.py index 9260042af..fb108b8eb 100644 --- a/test/unit/clitest/test_rcode.py +++ b/test/unit/clitest/test_rcode.py @@ -8,15 +8,12 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from builtins import object -from past.utils import old_div import os from omero_ext.path import path from omero.cli import BaseControl, CLI -omeroDir = old_div(path(os.getcwd()), "build") +omeroDir = path(os.getcwd()) / "build" class TestRCode(object): diff --git a/test/unit/clitest/test_script.py b/test/unit/clitest/test_script.py index 59cd5be3b..989decfec 100644 --- a/test/unit/clitest/test_script.py +++ b/test/unit/clitest/test_script.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object from omero.plugins.script import ScriptControl from omero.cli import CLI import pytest diff --git a/test/unit/clitest/test_sess.py b/test/unit/clitest/test_sess.py index 5a66316dc..82ebb3ef1 100644 --- a/test/unit/clitest/test_sess.py +++ b/test/unit/clitest/test_sess.py @@ -8,12 +8,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import unicode_literals -from __future__ import division -from builtins import str -from builtins import object -from past.utils import old_div import os import sys import pytest @@ -27,7 +22,7 @@ from omero.util.temp_files import create_path from omero.plugins.sessions import SessionsControl -omeroDir = old_div(path(os.getcwd()), "build") +omeroDir = path(os.getcwd()) / "build" testsess = "testsess" testuser = "testuser" @@ -224,9 +219,9 @@ def testSetCurrent(self, name, key, port, tmpdir): session_dir = tmpdir # Using last_* methods - assert (old_div(session_dir, "._LASTHOST_")).exists() + assert (session_dir / "._LASTHOST_").exists() assert "srv" == s.last_host() - assert (old_div(session_dir, "._LASTPORT_")).exists() + assert (session_dir / "._LASTPORT_").exists() assert (port or '4064') == s.last_port() # Using helpers diff --git a/test/unit/clitest/test_sessions.py b/test/unit/clitest/test_sessions.py index 688c4c348..dccd11c78 100644 --- a/test/unit/clitest/test_sessions.py +++ b/test/unit/clitest/test_sessions.py @@ -19,10 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from __future__ import division -from builtins import str -from builtins import object -from past.utils import old_div from omero.cli import CLI from omero.plugins.sessions import SessionsControl @@ -97,7 +93,7 @@ def testCustomSessionsDir( # args.session_dir sets the sessions dir args = Namespace() if session_args: - setattr(args, session_args, old_div(tmpdir, session_args)) + setattr(args, session_args, tmpdir / session_args) if environment.get('OMERO_SESSION_DIR') or session_args: store = pytest.deprecated_call(self.cli.controls['sessions'].store, args) @@ -106,7 +102,7 @@ def testCustomSessionsDir( # By order of precedence if environment.get('OMERO_SESSIONDIR'): - sdir = old_div(path(tmpdir), environment.get('OMERO_SESSIONDIR')) + sdir = path(tmpdir) / environment.get('OMERO_SESSIONDIR') elif environment.get('OMERO_SESSION_DIR'): sdir = (path(tmpdir) / environment.get('OMERO_SESSION_DIR') / 'omero' / 'sessions') diff --git a/test/unit/clitest/test_tag.py b/test/unit/clitest/test_tag.py index e7ad3022b..02126df89 100644 --- a/test/unit/clitest/test_tag.py +++ b/test/unit/clitest/test_tag.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object import pytest from omero.cli import CLI, NonZeroReturnCode from omero.plugins.tag import TagControl diff --git a/test/unit/clitest/test_user.py b/test/unit/clitest/test_user.py index ebabeea5a..06ea4e3b7 100644 --- a/test/unit/clitest/test_user.py +++ b/test/unit/clitest/test_user.py @@ -19,7 +19,6 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -from builtins import object from omero.plugins.user import UserControl from omero.cli import CLI import pytest diff --git a/test/unit/fstest/test_model.py b/test/unit/fstest/test_model.py index 456ba1813..ec6218a1f 100644 --- a/test/unit/fstest/test_model.py +++ b/test/unit/fstest/test_model.py @@ -25,7 +25,6 @@ just show creation / linkage scenarios. """ -from builtins import object import time import omero import omero.all diff --git a/test/unit/gatewaytest/test_argument_errors.py b/test/unit/gatewaytest/test_argument_errors.py index c0b8769e4..90c2e6d97 100644 --- a/test/unit/gatewaytest/test_argument_errors.py +++ b/test/unit/gatewaytest/test_argument_errors.py @@ -23,11 +23,7 @@ gateway tests - argument errors in gateway methods """ -from __future__ import division -from builtins import str -from builtins import object -from past.utils import old_div from omero.gateway import _BlitzGateway import pytest @@ -37,7 +33,7 @@ class TestArgumentErrors(object): @classmethod @pytest.fixture(autouse=True) def setup_class(cls, tmpdir, monkeypatch): - ice_config = old_div(tmpdir, "ice.config") + ice_config = tmpdir / "ice.config" ice_config.write("omero.host=localhost\nomero.port=4064") monkeypatch.setenv("ICE_CONFIG", "%s" % ice_config) cls.g = _BlitzGateway() diff --git a/test/unit/gatewaytest/test_build_query.py b/test/unit/gatewaytest/test_build_query.py index 135c58639..b12eeb655 100644 --- a/test/unit/gatewaytest/test_build_query.py +++ b/test/unit/gatewaytest/test_build_query.py @@ -21,7 +21,6 @@ """Gateway tests - buildQuery() as used by conn.getObjects().""" -from builtins import object from omero.gateway import _BlitzGateway, BlitzObjectWrapper, KNOWN_WRAPPERS from omero.sys import Parameters, ParametersI, Filter import pytest diff --git a/test/unit/gatewaytest/test_utils.py b/test/unit/gatewaytest/test_utils.py index 0091fb0dd..550d974bb 100644 --- a/test/unit/gatewaytest/test_utils.py +++ b/test/unit/gatewaytest/test_utils.py @@ -9,10 +9,6 @@ """ -from builtins import str -from past.builtins import basestring -from builtins import hex -from builtins import object from omero.gateway.utils import ServiceOptsDict from omero.gateway.utils import toBoolean from omero.gateway.utils import propertiesToDict @@ -30,7 +26,7 @@ def test_constructor(self): d = ServiceOptsDict(d) resd = d.get("omero.group") - assert isinstance(resd, basestring) + assert isinstance(resd, str) assert d.get("omero.group") == str(d["omero.group"]) d = ServiceOptsDict(x=1, y=2) diff --git a/test/unit/scriptstest/test_parse.py b/test/unit/scriptstest/test_parse.py index 72003b4da..cc805738e 100644 --- a/test/unit/scriptstest/test_parse.py +++ b/test/unit/scriptstest/test_parse.py @@ -8,10 +8,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import print_function -from builtins import str -from builtins import object import pytest from omero_ext.path import path diff --git a/test/unit/scriptstest/test_processor.py b/test/unit/scriptstest/test_processor.py index 74c827ac3..b3841ad2c 100644 --- a/test/unit/scriptstest/test_processor.py +++ b/test/unit/scriptstest/test_processor.py @@ -9,8 +9,6 @@ """ -from builtins import str -from builtins import object import os import sys import logging diff --git a/test/unit/scriptstest/test_prototypes.py b/test/unit/scriptstest/test_prototypes.py index 331123bbc..ea03dd7aa 100644 --- a/test/unit/scriptstest/test_prototypes.py +++ b/test/unit/scriptstest/test_prototypes.py @@ -9,8 +9,6 @@ """ -from builtins import str -from builtins import object import omero from omero.scripts import Long, List, validate_inputs from omero.rtypes import rmap, rint, rlong, rstring, rlist, rset, unwrap diff --git a/test/unit/tablestest/library.py b/test/unit/tablestest/library.py index 0f3527fb4..b6441c65c 100755 --- a/test/unit/tablestest/library.py +++ b/test/unit/tablestest/library.py @@ -10,7 +10,6 @@ """ -from builtins import object from omero.util.temp_files import create_path diff --git a/test/unit/tablestest/test_hdfstorage.py b/test/unit/tablestest/test_hdfstorage.py index 07eb91307..4950c65df 100755 --- a/test/unit/tablestest/test_hdfstorage.py +++ b/test/unit/tablestest/test_hdfstorage.py @@ -8,12 +8,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from __future__ import print_function -from builtins import str -from past.utils import old_div -from builtins import object import time import pytest import omero.columns @@ -85,7 +80,7 @@ def append(self, hdf, map): def hdfpath(self): tmpdir = self.tmpdir() - return old_div(path(tmpdir), "test.h5") + return path(tmpdir) / "test.h5" def testInvalidFile(self): pytest.raises( @@ -223,7 +218,7 @@ def testVersion(self): def testHandlesExistingDirectory(self): t = path(self.tmpdir()) - h = old_div(t, "test.h5") + h = t / "test.h5" assert t.exists() hdf = HdfStorage(h, self.lock) hdf.cleanup() @@ -498,7 +493,7 @@ class TestHdfList(TestCase): def hdfpath(self): tmpdir = self.tmpdir() - return old_div(path(tmpdir), "test.h5") + return path(tmpdir) / "test.h5" def testLocking(self, monkeypatch, mocker): lock1 = threading.RLock() diff --git a/test/unit/tablestest/test_servants.py b/test/unit/tablestest/test_servants.py index b5419c043..3d3621b33 100755 --- a/test/unit/tablestest/test_servants.py +++ b/test/unit/tablestest/test_servants.py @@ -8,13 +8,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from builtins import str -from builtins import range -from future.utils import native_str -from past.utils import old_div -from builtins import object import pytest import Ice import omero @@ -96,7 +90,7 @@ def __call__(self, *args, **kwargs): class mocked_service_factory(object): def __init__(self): - self.db_uuid = native_str(uuid.uuid4()) + self.db_uuid = str(uuid.uuid4()) self.return_values = [] def keepAlive(self, *args): @@ -164,7 +158,7 @@ def get(self, *args): class mock_internal_repo(object): def __init__(self, dir): - self.path = old_div(dir, "mock.h5") + self.path = dir / "mock.h5" def __call__(self, *args): return self @@ -254,7 +248,7 @@ def repouuid(self): def repodir(self, make=True): self.tmp = path(self.tmpdir()) self.communicator.getProperties().setProperty("omero.repo.dir", - native_str(self.tmp)) + str(self.tmp)) repo = self.tmp / ".omero" / "repository" if make: repo.makedirs() @@ -264,9 +258,9 @@ def repofile(self, db_uuid, repo_uuid=None): if repo_uuid is None: repo_uuid = self.repouuid() f = self.repodir() - f = old_div(path(f), db_uuid) + f = path(f) / db_uuid f.makedirs() - f = old_div(f, "repo_uuid") + f = f / "repo_uuid" f.write_lines([repo_uuid]) # Note: some of the following method were added as __init__ called diff --git a/test/unit/test_clients.py b/test/unit/test_clients.py index c6c8a93aa..c729b120e 100644 --- a/test/unit/test_clients.py +++ b/test/unit/test_clients.py @@ -18,7 +18,6 @@ */ """ -from builtins import object import pytest import Ice import logging diff --git a/test/unit/test_config.py b/test/unit/test_config.py index 4f09a92a9..4d29f6198 100755 --- a/test/unit/test_config.py +++ b/test/unit/test_config.py @@ -8,11 +8,7 @@ * Use is subject to license terms supplied in LICENSE.txt */ """ -from __future__ import division -from builtins import str -from builtins import object -from past.utils import old_div import os import sys import json @@ -347,14 +343,14 @@ def testReadOnlyConfigFailsOnEnv2(self, tmp_path): def testCannotCreate(self, tmp_path): d = tmp_path d.chmod(0o555) - filename = str(old_div(d, "config.xml")) + filename = str(d / "config.xml") with pytest.raises(IOError) as excinfo: ConfigXml(filename).close() assert excinfo.value.errno == errno.EACCES def testCannotCreateLock(self, tmp_path): d = tmp_path - filename = str(old_div(d, "config.xml")) + filename = str(d / "config.xml") lock_filename = "%s.lock" % filename with open(lock_filename, "w") as fo: fo.write("dummy\n") diff --git a/test/unit/test_conversions.py b/test/unit/test_conversions.py index 22422184f..5d8c68a1f 100644 --- a/test/unit/test_conversions.py +++ b/test/unit/test_conversions.py @@ -23,8 +23,6 @@ Simple tests of the new conversions used for units. """ -from builtins import str -from builtins import object from pytest import assertAlmostEqual from omero.conversions import Add from omero.conversions import Int diff --git a/test/unit/test_gateway.py b/test/unit/test_gateway.py index 3f34480ca..7e1839b19 100644 --- a/test/unit/test_gateway.py +++ b/test/unit/test_gateway.py @@ -24,7 +24,6 @@ Test of various things under omero.gateway """ -from builtins import object import Ice import pytest import sys @@ -84,12 +83,6 @@ class TestObjectsUnicode(object): Tests that ExperimenterWrapper methods return correct unicode """ - def _encode(self, s): - if sys.version_info >= (3, 0, 0): - return s - else: - return s.encode('utf8') - def test_experimenter(self): """ Tests methods handled by BlitzObjectWrapper.__getattr__ @@ -117,9 +110,9 @@ def test_project(self): proj = MockConnection(project).getObject("Project", 1) # getName is of type String - assert proj.getName() == self._encode(name) + assert proj.getName() == name assert proj.name == name - assert proj.getDescription() == self._encode(desc) + assert proj.getDescription() == desc assert proj.description == desc def test_tag_annotation(self): @@ -131,9 +124,9 @@ def test_tag_annotation(self): obj.ns = rstring(ns) tag = MockConnection(obj).getObject("Annotation", 1) - assert tag.getValue() == self._encode(text_value) + assert tag.getValue() == text_value assert tag.textValue == text_value - assert tag.getNs() == self._encode(ns) + assert tag.getNs() == ns assert tag.ns == ns def test_file_annotation(self): @@ -145,7 +138,7 @@ def test_file_annotation(self): obj.file = f file_ann = MockConnection(obj).getObject("Annotation", 1) - assert file_ann.getFileName() == self._encode(file_name) + assert file_ann.getFileName() == file_name def test_map_annotation(self): """Tests MapAnnotationWrapper.getValue() returns unicode""" @@ -166,7 +159,7 @@ def test_plate(self): obj.name = rstring(name) plate = MockConnection(obj).getObject("Plate", 1) - assert plate.getName() == self._encode(name) + assert plate.getName() == name plate._gridSize = {'rows': rows, 'columns': cols} assert plate.getColumnLabels() == [c for c in range(1, cols + 1)] assert plate.getRowLabels() == ['A', 'B', 'C'] @@ -188,12 +181,6 @@ class TestBlitzObjectGetAttr(object): Tests returning objects via the BlitzObject.__getattr__ """ - def _encode(self, s): - if sys.version_info >= (3, 0, 0): - return s - else: - return s.encode('utf8') - def test_logical_channel(self): name = u'₩€_name_$$' ill_val = u'πλζ.test.ζ' @@ -238,13 +225,13 @@ def __loadedHotSwap__(self): pass channel = MockChannel(None, obj) - assert channel.getName() == self._encode(name) + assert channel.getName() == name assert channel.name == name assert channel.getPinHoleSize().getValue() == ph_size assert channel.getPinHoleSize().getUnit() == ph_units assert channel.getPinHoleSize().getSymbol() == 'µm' # Illumination is an enumeration - assert channel.getIllumination().getValue() == self._encode(ill_val) + assert channel.getIllumination().getValue() == ill_val assert channel.getExcitationWave().getValue() == ex_wave assert channel.getExcitationWave().getUnit() == ex_units assert channel.getExcitationWave().getSymbol() == 'Å' diff --git a/test/unit/test_jvmcfg.py b/test/unit/test_jvmcfg.py index 50126a4fa..81cd41438 100644 --- a/test/unit/test_jvmcfg.py +++ b/test/unit/test_jvmcfg.py @@ -22,12 +22,7 @@ """ Test of the automatic JVM setting logic for OMERO startup. """ -from __future__ import division - -from builtins import str -from past.utils import old_div -from builtins import object import pytest import os @@ -214,7 +209,7 @@ def validate(self, rv): def template_xml(): - templates = old_div(path(OMERODIR), "..") + templates = path(OMERODIR) / ".." templates = templates / "etc" / "templates" / "grid" / "templates.xml" templates = templates.abspath() return XML(templates.text()) @@ -241,7 +236,7 @@ def test_12527(self, fixture, monkeypatch): monkeypatch.setattr(Strategy, '_system_memory_mb_java', lambda x: (2000, 4000)) p = write_config(fixture.input) - old_templates = old_div(path(__file__).dirname(), "old_templates.xml") + old_templates = path(__file__).dirname() / "old_templates.xml" xml = XML(old_templates.abspath().text()) config = ConfigXml(filename=str(p), env_config="default") with pytest.raises(Exception): diff --git a/test/unit/test_metadata_mapannotations.py b/test/unit/test_metadata_mapannotations.py index f70ed2c3a..45eba1253 100644 --- a/test/unit/test_metadata_mapannotations.py +++ b/test/unit/test_metadata_mapannotations.py @@ -24,9 +24,6 @@ """ -from __future__ import unicode_literals -from builtins import str -from builtins import object import pytest from omero.model import MapAnnotationI, NamedValue diff --git a/test/unit/test_metadata_utils.py b/test/unit/test_metadata_utils.py index 48f596315..985ba3aa3 100644 --- a/test/unit/test_metadata_utils.py +++ b/test/unit/test_metadata_utils.py @@ -22,11 +22,7 @@ """ Test of metadata_utils classes """ -from __future__ import print_function -from __future__ import unicode_literals - -from builtins import object import pytest from omero.util.metadata_utils import ( diff --git a/test/unit/test_model.py b/test/unit/test_model.py index 9e6184121..a6d60192a 100644 --- a/test/unit/test_model.py +++ b/test/unit/test_model.py @@ -9,12 +9,7 @@ Use is subject to license terms supplied in LICENSE.txt """ -from __future__ import division -from builtins import str -from builtins import range -from past.utils import old_div -from builtins import object import pytest import omero import omero.clients @@ -358,7 +353,7 @@ def testEnumerators(self, ul): def testCtorConversions(self): nm = LengthI(1.0, omero.model.enums.UnitsLength.NANOMETER) ang = LengthI(nm, omero.model.enums.UnitsLength.ANGSTROM) - assert nm.getValue() == old_div(ang.getValue(), 10) + assert nm.getValue() == ang.getValue() // 10 def testLengthGetSymbol(self): um = LengthI(1.0, omero.model.enums.UnitsLength.MICROMETER) diff --git a/test/unit/test_parameters.py b/test/unit/test_parameters.py index 2844e2055..c46b67904 100644 --- a/test/unit/test_parameters.py +++ b/test/unit/test_parameters.py @@ -10,7 +10,6 @@ """ -from builtins import object from omero.rtypes import rlong, rint, rbool, rstring, rtime from omero_sys_ParametersI import ParametersI diff --git a/test/unit/test_path.py b/test/unit/test_path.py index a7e576e74..ccfa1415c 100644 --- a/test/unit/test_path.py +++ b/test/unit/test_path.py @@ -7,10 +7,7 @@ Copyright 2014 CRS4. All rights reserved. Use is subject to license terms supplied in LICENSE.txt. """ -from __future__ import division -from builtins import object -from past.utils import old_div import omero_ext.path as path @@ -18,8 +15,8 @@ class TestPath(object): def test_parpath(self): root = path.path('/') - a1, a2 = [old_div(root, _) for _ in ('a1', 'a2')] - b = old_div(a1, 'b') + a1, a2 = [root / _ for _ in ('a1', 'a2')] + b = a1 / 'b' for x, y in (root, a1), (root, a2), (a1, b): assert len(y.parpath(x)) == 1 assert len(x.parpath(y)) == 0 diff --git a/test/unit/test_permissions.py b/test/unit/test_permissions.py index 82472f40b..9abff5de4 100644 --- a/test/unit/test_permissions.py +++ b/test/unit/test_permissions.py @@ -9,8 +9,6 @@ Use is subject to license terms supplied in LICENSE.txt """ -from builtins import str -from builtins import object import omero.model diff --git a/test/unit/test_python_only.py b/test/unit/test_python_only.py index d539835fc..aec6f2a0a 100644 --- a/test/unit/test_python_only.py +++ b/test/unit/test_python_only.py @@ -9,7 +9,6 @@ """ -from builtins import object import pytest import omero import Ice diff --git a/test/unit/test_rois.py b/test/unit/test_rois.py index 48c5a486b..47c3b81f1 100644 --- a/test/unit/test_rois.py +++ b/test/unit/test_rois.py @@ -23,7 +23,6 @@ Simple tests of various ROI utilities """ -from builtins import object from omero.util.ROI_utils import pointsStringToXYlist, xyListToBbox from omero.util.roi_handling_utils import points_string_to_xy_list diff --git a/test/unit/test_rtypes.py b/test/unit/test_rtypes.py index d4e590985..1d8ffd832 100644 --- a/test/unit/test_rtypes.py +++ b/test/unit/test_rtypes.py @@ -8,10 +8,6 @@ * Use is subject to license terms supplied in LICENSE.txt */ """ -from builtins import str -from builtins import object -from future.utils import native_str -from past.builtins import long import sys import pytest import omero @@ -33,10 +29,6 @@ def testConversionMethod(self): # Unsupported # assert rdouble(0) == rtype(Double.valueOf(0)) assert rfloat(0) == rtype(float(0)) - if sys.version_info < (3, 0, 0): - assert rlong(0) == rtype(long(0)) - else: - assert rint(0) == rtype(long(0)) assert rint(0) == rtype(int(0)) assert rstring("string") == rtype("string") # Unsupported @@ -277,8 +269,8 @@ def testGetAttrWorks(self): def testPassThroughNoneAndRTypes(self): """ - To prevent having to check for isintance(int,...) or - isintance(RInt,...) all over the place, the static methods + To prevent having to check for isinstance(int,...) or + isinstance(RInt,...) all over the place, the static methods automatically check for acceptable types and simply pass them through. Similarly, the primitive types all check for None and return a null RType if necessary. @@ -454,7 +446,7 @@ def testResuingClass(self): ctor2 = myLongFromString.__class__("5") assert ctor1.val == ctor2.val - nu = native_str("u") + nu = "u" bu = str("u") cn = '中國' cnu = u'中國' diff --git a/test/unit/test_tempfiles.py b/test/unit/test_tempfiles.py index f9fa617ff..54f030dcf 100644 --- a/test/unit/test_tempfiles.py +++ b/test/unit/test_tempfiles.py @@ -8,11 +8,7 @@ * Use is subject to license terms supplied in LICENSE.txt */ """ -from __future__ import division -from builtins import str -from builtins import object -from past.utils import old_div import logging logging.basicConfig(level=0) @@ -63,7 +59,7 @@ def testFolderSimple(self): def testFolderWrite(self): p = self.testFolderSimple() - f = old_div(p, "file") + f = p / "file" f.write_text("hi") return p diff --git a/test/unit/test_util.py b/test/unit/test_util.py index 6334de2a2..38e4f2eac 100644 --- a/test/unit/test_util.py +++ b/test/unit/test_util.py @@ -23,14 +23,7 @@ """ Test of various things under omero.util """ -from __future__ import division -from __future__ import unicode_literals - -from builtins import str -from builtins import range -from future.utils import native_str -from past.utils import old_div -from builtins import object + import json import pytest from omero_ext.path import path @@ -43,10 +36,7 @@ get_omero_userdir, get_omero_user_cache_dir, get_user_dir) from omero_version import omero_version import omero.util.image_utils as image_utils -try: - from PIL import Image -except ImportError: - import Image +from PIL import Image import numpy @@ -216,10 +206,10 @@ def testTmpdirEnvironment(self, monkeypatch, tmpdir, environment): for var in list(environment.keys()): if environment[var]: monkeypatch.setenv( - native_str(var), - native_str(old_div(tmpdir, environment.get(var)))) + var, + str(tmpdir / environment.get(var))) else: - monkeypatch.delenv(native_str(var), raising=False) + monkeypatch.delenv(var, raising=False) if environment.get('OMERO_TEMPDIR'): value = pytest.deprecated_call(manager.tmpdir) @@ -227,7 +217,7 @@ def testTmpdirEnvironment(self, monkeypatch, tmpdir, environment): value = manager.tmpdir() if environment.get('OMERO_TMPDIR'): - tdir = old_div(tmpdir, environment.get('OMERO_TMPDIR')) + tdir = tmpdir / environment.get('OMERO_TMPDIR') elif environment.get('OMERO_TEMPDIR'): tdir = tmpdir / environment.get('OMERO_TEMPDIR') / "omero" / "tmp" elif environment.get('OMERO_USERDIR'): @@ -239,9 +229,9 @@ def testTmpdirEnvironment(self, monkeypatch, tmpdir, environment): def testTmpdir2805_1(self, monkeypatch, tmpdir): - monkeypatch.setenv(native_str('OMERO_TEMPDIR'), native_str(tmpdir)) - monkeypatch.delenv(native_str('OMERO_USERDIR'), raising=False) - tmpfile = old_div(tmpdir, 'omero') + monkeypatch.setenv('OMERO_TEMPDIR', str(tmpdir)) + monkeypatch.delenv('OMERO_USERDIR', raising=False) + tmpfile = tmpdir / 'omero' tmpfile.write('') value = pytest.deprecated_call(manager.tmpdir) @@ -249,11 +239,11 @@ def testTmpdir2805_1(self, monkeypatch, tmpdir): def testTmpdir2805_2(self, monkeypatch, tmpdir): - monkeypatch.setenv(native_str('OMERO_TEMPDIR'), native_str(tmpdir)) - monkeypatch.delenv(native_str('OMERO_USERDIR'), raising=False) - tempdir = old_div(tmpdir, 'omero') + monkeypatch.setenv('OMERO_TEMPDIR', str(tmpdir)) + monkeypatch.delenv('OMERO_USERDIR', raising=False) + tempdir = tmpdir / 'omero' tempdir.mkdir() - tmpfile = old_div(tempdir, 'tmp') + tmpfile = tempdir / 'tmp' tmpfile.write('') value = pytest.deprecated_call(manager.tmpdir) diff --git a/tox.ini b/tox.ini index f51c998ab..9b4e9ec30 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py38, py39, py310, py311 +envlist = py38, py39, py310, py311, py312 # https://tox.readthedocs.io/en/latest/config.html#conf-requires # Ensure pip is new enough requires = pip >= 19.0.0 @@ -9,7 +9,7 @@ requires = pip >= 19.0.0 # For environment markers see # https://www.python.org/dev/peps/pep-0508/#environment-markers deps = - future + setuptools numpy Pillow pytest @@ -22,7 +22,8 @@ deps = https://github.com/ome/zeroc-ice-py-github-ci/releases/download/0.2.0/zeroc_ice-3.6.5-cp38-cp38-linux_x86_64.whl; platform_system=="Linux" and python_version=="3.8" https://github.com/ome/zeroc-ice-py-github-ci/releases/download/0.2.0/zeroc_ice-3.6.5-cp39-cp39-linux_x86_64.whl; platform_system=="Linux" and python_version=="3.9" https://github.com/ome/zeroc-ice-py-github-ci/releases/download/0.2.0/zeroc_ice-3.6.5-cp310-cp310-linux_x86_64.whl; platform_system=="Linux" and python_version=="3.10" - https://github.com/glencoesoftware/zeroc-ice-py-linux-x86_64/releases/download/20231024/zeroc_ice-3.6.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl; platform_system=="Linux" and python_version=="3.11" + https://github.com/glencoesoftware/zeroc-ice-py-linux-x86_64/releases/download/20240202/zeroc_ice-3.6.5-cp311-cp311-manylinux_2_28_x86_64.whl; platform_system=="Linux" and python_version=="3.11" + https://github.com/glencoesoftware/zeroc-ice-py-linux-x86_64/releases/download/20240202/zeroc_ice-3.6.5-cp312-cp312-manylinux_2_28_x86_64.whl; platform_system=="Linux" and python_version=="3.12" https://github.com/glencoesoftware/zeroc-ice-py-macos-x86_64/releases/download/20220722/zeroc_ice-3.6.5-cp38-cp38-macosx_10_15_x86_64.whl; platform_system!="Windows" and platform_system!="Linux" and python_version=="3.8" https://github.com/glencoesoftware/zeroc-ice-py-macos-x86_64/releases/download/20220722/zeroc_ice-3.6.5-cp39-cp39-macosx_10_15_x86_64.whl; platform_system!="Windows" and platform_system!="Linux" and python_version=="3.9" https://github.com/glencoesoftware/zeroc-ice-py-macos-x86_64/releases/download/20220722/zeroc_ice-3.6.5-cp310-cp310-macosx_10_15_x86_64.whl; platform_system!="Windows" and platform_system!="Linux" and python_version=="3.10"