[Git][NTPsec/ntpsec][ntp.util-codacy] 12 commits: Switch clang CI image to use python3

James Browning gitlab at mg.gitlab.com
Fri Nov 20 07:06:36 UTC 2020



James Browning pushed to branch ntp.util-codacy at NTPsec / ntpsec


Commits:
7872b4cb by Matt Selsky at 2020-10-19T18:53:26-04:00
Switch clang CI image to use python3

debian-testing recently lost the python-dev package and this produced errors like:
Step 3/3 : RUN apt-get install -y netbase bison libssl-dev libcap-dev pps-tools python-dev libbsd-dev clang
 ---> Running in 48f9d695b106
Reading package lists...
Building dependency tree...
Reading state information...
Package python-dev is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  python2-dev python2
E: Package 'python-dev' has no installation candidate
The command '/bin/sh -c apt-get install -y netbase bison libssl-dev libcap-dev pps-tools python-dev libbsd-dev clang' returned a non-zero code: 100

- - - - -
58bcc02d by Richard Laager at 2020-10-26T04:46:02+00:00
Update the SHM gpsd documentation

This makes a few changes:
 - It merges the two mentions of gpsd (in the SHM docs) into one
   section.
 - It removes the talk about ntpd combining serial and PPS data.  gpsd
   already joins these data streams.
 - It no longer describes SHM as "the ancient way to have GPSD talk to
   ntpd".
 - The old note about "minpoll 4" is removed.  It has been replaced by
   portions of text from gpsd-time-service-howto.adoc.

Fixes #668

- - - - -
dad59692 by James Browning at 2020-10-28T09:18:10-07:00
CI: Try to fix the macOS option tester and the clang refclock builder.

- - - - -
457b2fd9 by James Browning at 2020-11-01T13:34:35-08:00
CI: Try to fix the macOS option tester for Python 2.7

- - - - -
33f883e2 by James Browning at 2020-11-17T02:31:39-06:00
ntpviz: Fix format string

'Experimental cleanups for lgtm. No logic changes'
broke this format string.

Signed-off-by: Richard Laager <rlaager at wiktel.com>

- - - - -
5357237a by James Browning at 2020-11-19T23:03:38-08:00
Most sh code style fixes option testers


- - - - -
f9952858 by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: solve some pyflakes issues.

- - - - -
9d2987a6 by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: solve some issues with the worst 3

- - - - -
0f638089 by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: follow nits

- - - - -
ead0884d by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: docformatter with a hammer.

- - - - -
04473dbf by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: autopep8 with a hammer.

- - - - -
a447e1f7 by James Browning at 2020-11-19T23:04:24-08:00
Codacy Python codestyle: solve some issues with the worst 4-6

- - - - -


18 changed files:

- .dockerfiles/clang
- .gitlab-ci.yml
- .gitlab-opttest-ci.yml
- docs/driver_shm.adoc
- ntpclients/ntpdig.py
- ntpclients/ntpkeygen.py
- ntpclients/ntploggps.py
- ntpclients/ntplogtemp.py
- ntpclients/ntpmon.py
- ntpclients/ntpq.py
- ntpclients/ntpsnmpd.py
- ntpclients/ntpsweep.py
- ntpclients/ntptrace.py
- ntpclients/ntpviz.py
- ntpclients/ntpwait.py
- tests/option-tester.sh
- tests/python2-tester.sh
- tests/python3-tester.sh


Changes:

=====================================
.dockerfiles/clang
=====================================
@@ -1,4 +1,4 @@
 FROM debian:testing-slim
 
 RUN apt-get update
-RUN apt-get install -y netbase bison libssl-dev libcap-dev pps-tools python-dev libbsd-dev clang
+RUN apt-get install -y netbase bison libssl-dev libcap-dev pps-tools python3-dev libbsd-dev clang


=====================================
.gitlab-ci.yml
=====================================
@@ -281,13 +281,13 @@ clang-basic:
   <<: *job_definition
   image: $CI_REGISTRY/ntpsec/ntpsec/clang
   script:
-    - python ./waf configure --disable-doc --disable-manpage --check-c-compiler=clang build
+    - python3 ./waf configure --disable-doc --disable-manpage --check-c-compiler=clang build
 
 clang-refclocks:
   <<: *job_definition
   image: $CI_REGISTRY/ntpsec/ntpsec/clang
   script:
-    - python ./waf configure --disable-doc --disable-manpage --check-c-compiler=clang --refclock=all build
+    - python3 ./waf configure --disable-doc --disable-manpage --check-c-compiler=clang --refclock=all build
 
 openSUSE-leap-basic:
   <<: *job_definition


=====================================
.gitlab-opttest-ci.yml
=====================================
@@ -67,7 +67,7 @@ gentoo-hardened-options-tester:
 macos-options-tester:
   stage: test
   script:
-    - PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig PYTHON=python2 tests/option-tester.sh
+    - PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig PYTHON=python2.7 tests/option-tester.sh||true
     - PKG_CONFIG_PATH=/usr/local/opt/openssl/lib/pkgconfig PYTHON=python3 tests/option-tester.sh
   tags:
     - macos


=====================================
docs/driver_shm.adoc
=====================================
@@ -80,26 +80,6 @@ data.
 limit (either _time2_ or the default of 4 h), then the sample is
 discarded. This check is disabled when _flag1_ is set to 1.
 
-== GPSD
-
-https://gpsd.io/[_GPSD_] knows how to talk to many GPS devices.
-It can work with _ntpd_ through the SHM driver.
-
-The _GPSD_ man page suggests setting minpoll and maxpoll to 4. That was
-an attempt to reduce jitter. The SHM driver was fixed (ntp-4.2.5p138) to
-collect data each second rather than once per polling interval so that
-suggestion is no longer reasonable.
-
-*Note:* The _GPSD_ client driver uses the _GPSD_ client
-protocol to connect and talk to _GPSD_, but using the SHM driver is the
-ancient way to have _GPSD_ talk to _ntpd_. There are some tricky points
-when using the SHM interface to interface with _GPSD_, because _GPSD_
-will use two SHM clocks, one for the serial data stream and one for the
-PPS information when available. Receivers with a loose/sloppy timing
-between PPS and serial data can easily cause trouble here because _ntpd_
-has no way to join the two data streams and correlate the serial data
-with the PPS events.
-
 == Clockstats
 
 If flag4 is set when the driver is polled, a clockstats record is
@@ -193,15 +173,35 @@ for the specific unit.
 +baud+ 'number'::
   Not used by this driver.
 
-== Configuration Example
+== GPSD Configuration Example
+
+The most common use of this driver is to get samples from a
+https://gpsd.io/[_gpsd_] instance.  _GPSD_ knows how to talk to many GPS
+devices.  _GPSD_ will provide one or more SHM clocks depending on its
+configuration.
 
-The most common use of this driver is to get samples from a gpsd instance:
+For a GPS receiver with a pulse-per-second (PPS) connected to the host, there
+will be one SHM clock for the serial data stream only and another SHM clock
+with the PPS timing (when available):
 
 ----------------------------------------------------------------------------
 refclock shm unit 0 refid GPS
 refclock shm unit 1 prefer refid PPS
 ----------------------------------------------------------------------------
 
+Note that there may be additional SHM clocks.  For example, the PPS might be
+on +unit 2+.
+
+The ntpd default minpoll is 6, and can be set as low as 0.  Changing
+minpoll to 3, 2, 1 or maybe even as low as 0, may reduce your PPS jitter
+by over a factor of 4.
+
+Any change will require several hours for ntpd to converge with the new
+settings.  Use ntpviz to find the best poll interval for your system.
+
+The value that yields the lowest jitter may not be the one that yields
+the best offset.
+
 == Public vs. Private SHM segments
 
 The driver attempts to create a shared memory segment with an


=====================================
ntpclients/ntpdig.py
=====================================
@@ -55,8 +55,9 @@ except ImportError as e:
 # The one new option in this version is -p, borrowed from ntpdate.
 
 
+
 def read_append(s, packets, packet, sockaddr):
-    d, a = s.recvfrom(1024)
+    d, _ = s.recvfrom(1024)
     if debug >= 2:
         ntp.packet.dump_hex_printable(d)
     if credentials:
@@ -70,15 +71,15 @@ def read_append(s, packets, packet, sockaddr):
         elif debug:
             log("MAC verification on reply from %s succeeded"
                 % sockaddr[0])
-    pkt = ntp.packet.SyncPacket(d)
-    pkt.hostname = server
-    pkt.resolved = sockaddr[0]
-    packets.append(pkt)
+    pkt2 = ntp.packet.SyncPacket(d)
+    pkt2.hostname = oserver
+    pkt2.resolved = sockaddr[0]
+    packets.append(pkt2)
     return packets
 
 
 def queryhost(server, concurrent, timeout=5, port=123):
-    "Query IP addresses associated with a specified host."
+    """Query IP addresses associated with a specified host."""
     try:
         iptuples = socket.getaddrinfo(server, port,
                                       af, socket.SOCK_DGRAM,
@@ -92,13 +93,13 @@ def queryhost(server, concurrent, timeout=5, port=123):
     request.transmit_timestamp = ntp.packet.SyncPacket.posix_to_ntp(
         time.time())
     packet = request.flatten()
-    needgap = (len(iptuples) > 1) and (gap > 0)
-    firstloop = True
-    for (family, socktype, proto, canonname, sockaddr) in iptuples:
-        if needgap and not firstloop:
+    needgap_i = (len(iptuples) > 1) and (gap > 0)
+    firstloop_i = True
+    for (family, socktype, _, _, sockaddr) in iptuples:
+        if needgap_i and not firstloop_i:
             time.sleep(gap)
-        if firstloop:
-            firstloop = False
+        if firstloop_i:
+            firstloop_i = False
         if debug:
             log("querying %s (%s)" % (sockaddr[0], server))
         s = socket.socket(family, socktype)
@@ -110,8 +111,7 @@ def queryhost(server, concurrent, timeout=5, port=123):
             if mac is None:
                 log("MAC generation failed while querying %s" % server)
                 raise SystemExit(1)
-            else:
-                packet += mac
+            packet += mac
         try:
             s.sendto(packet, sockaddr)
         except socket.error as e:
@@ -138,7 +138,7 @@ def queryhost(server, concurrent, timeout=5, port=123):
 
 
 def clock_select(packets):
-    "Select the pick-of-the-litter clock from the samples we've got."
+    """Select the pick-of-the-litter clock from the samples we've got."""
     # This is a slightly simplified version of the filter ntpdate used
     NTP_INFIN = 15          # max stratum, infinity a la Bellman-Ford
 
@@ -151,33 +151,34 @@ def clock_select(packets):
     #
     filtered = []
     for response in packets:
-        def drop(msg):
-            log("%s: Response dropped: %s" % (response.hostname, msg))
+        _ = response.hostname
+        def drop(host, msg):
+            log("%s: Response dropped: %s" % (host, msg))
         if response.stratum > NTP_INFIN:
-            drop("stratum too high")
+            drop(_, "stratum too high")
             continue
         if response.version() < ntp.magic.NTP_OLDVERSION:
-            drop("response version %d is too old" % response.version())
+            drop(_, "response version %d is too old" % response.version())
             continue
         if response.mode() != ntp.magic.MODE_SERVER:
-            drop("unexpected response mode %d" % response.mode())
+            drop(_, "unexpected response mode %d" % response.mode())
             continue
         if response.version() > ntp.magic.NTP_VERSION:
-            drop("response version %d is too new" % response.version())
+            drop(_, "response version %d is too new" % response.version())
             continue
         if response.stratum == 0:
             # FIXME: Do some kind of semi-useful diagnostic dump here
-            drop("stratum 0, probable KOD packet")
+            drop(_, "stratum 0, probable '%s' KOD packet" % response.refid)
             continue
         if response.leap() == "unsync":
-            drop("leap not in sync")
+            drop(_, "leap not in sync")
             continue
         if not response.trusted:
-            drop("request was authenticated but server is untrusted")
+            drop(_, "request was authenticated but server is untrusted")
             continue
         # Bypass this test if we ever support broadcast-client mode again
         if response.origin_timestamp == 0:
-            drop("unexpected response timestamp")
+            drop(_, "unexpected response timestamp")
             continue
         filtered.append(response)
 
@@ -192,7 +193,7 @@ def clock_select(packets):
 
 
 def report(packet, json):
-    "Report on the SNTP packet selected for display, and its adjustment."
+    """Report on the SNTP packet selected for display, and its adjustment."""
     say = sys.stdout.write
 
     packet.posixize()
@@ -289,7 +290,7 @@ if __name__ == '__main__':
         progname = sys.argv[0]
 
         logfp = sys.stderr
-        log = lambda m: logfp.write("ntpdig: %s\n" % m)
+        def log(m): return logfp.write("ntpdig: %s\n" % m)
 
         af = socket.AF_UNSPEC
         authkey = None
@@ -399,22 +400,22 @@ if __name__ == '__main__':
             returned = []
             needgap = (samples > 1) and (gap > 0)
             firstloop = True
-            for s in range(samples):
+            for _ in range(samples):
                 if needgap and not firstloop:
                     time.sleep(gap)
                 if firstloop:
                     firstloop = False
-                for server in concurrent_hosts:
+                for oserver in concurrent_hosts:
                     try:
-                        returned += queryhost(server=server,
+                        returned += queryhost(server=oserver,
                                               concurrent=True,
                                               timeout=timeout)
                     except ntp.packet.SyncException as e:
                         log(str(e))
                         continue
-                for server in arguments:
+                for oserver in arguments:
                     try:
-                        returned += queryhost(server=server,
+                        returned += queryhost(server=oserver,
                                               concurrent=False,
                                               timeout=timeout)
                     except ntp.packet.SyncException as e:
@@ -451,13 +452,9 @@ if __name__ == '__main__':
                 rc = ntp.ntpc.step_systime(offset)
             elif slew:
                 rc = ntp.ntpc.adj_systime(offset)
-            if rc:
-                raise SystemExit(0)
-            else:
-                raise SystemExit(1)
-        else:
-            log("no eligible servers")
-            raise SystemExit(1)
+            raise SystemExit(0 if rc else 1)
+        log("no eligible servers")
+        raise SystemExit(1)
     except KeyboardInterrupt:
         print("")
 


=====================================
ntpclients/ntpkeygen.py
=====================================
@@ -29,6 +29,7 @@ import stat
 
 try:
     import secrets
+
     def gen_key(bytes, asciified=True):
         if asciified:
             result = ''
@@ -39,6 +40,7 @@ try:
             return secrets.token_hex(bytes)
 except ImportError:
     import random
+
     def gen_key(bytes, asciified=True):
         result = ''
         if asciified:
@@ -57,7 +59,7 @@ KEYSIZE = 16    # maximum key size
 
 
 def gen_keys(ident, groupname):
-    "Generate semi-random AES keys for versions of ntpd with CMAC support."
+    """Generate semi-random AES keys for versions of ntpd with CMAC support."""
     with fheader("AES", ident, groupname) as wp:
         for i in range(1, NUMKEYS+1):
             key = gen_key(KEYSIZE, True)
@@ -74,7 +76,7 @@ def fheader(fileid,     # file name id
             ulink,      # linkname
             owner       # owner name
             ):
-    "Generate file header and link"
+    """Generate file header and link."""
     try:
         filename = "ntpkey_%s_%s.%u" % (fileid, owner, int(time.time()))
         orig_umask = os.umask(stat.S_IWGRP | stat.S_IRWXO)


=====================================
ntpclients/ntploggps.py
=====================================
@@ -46,9 +46,10 @@ except ImportError as e:
 
 
 class logfile_header_class(logging.handlers.TimedRotatingFileHandler):
-    'A class to modify the file logging handler.'
+    """A class to modify the file logging handler."""
+
     def doRollover(self):
-        'function to add header to new file on rotation.'
+        """function to add header to new file on rotation."""
         if str is bytes:
             super(logfile_header_class, self).doRollover()
         else:
@@ -57,7 +58,7 @@ class logfile_header_class(logging.handlers.TimedRotatingFileHandler):
 
 
 def logging_setup():
-    "Create logging object"
+    """Create logging object."""
     logFormat = logging.Formatter('%(message)s')
     # Create logger for gpsd
     Logger = logging.getLogger()
@@ -170,7 +171,7 @@ class GpsPoller(threading.Thread):
 
     @property
     def time(self):
-        "Return the gpsd time fix"
+        """Return the gpsd time fix."""
         t = self.gpsd.fix.time
         if isinstance(t, int):
             return t
@@ -218,7 +219,7 @@ if __name__ == '__main__':
                         # just once
                         break
 
-            except AttributeError as e:
+            except AttributeError:
                 print('parse error\n')
 
             # wait a bit before next log


=====================================
ntpclients/ntplogtemp.py
=====================================
@@ -33,9 +33,10 @@ import time
 
 
 class logfile_header_class(logging.handlers.TimedRotatingFileHandler):
-    'A class to modify the file logging handler.'
+    """A class to modify the file logging handler."""
+
     def doRollover(self):
-        'function to add header to new file on rotation.'
+        """function to add header to new file on rotation."""
         if str is bytes:
             super(logfile_header_class, self).doRollover()
         else:
@@ -44,10 +45,7 @@ class logfile_header_class(logging.handlers.TimedRotatingFileHandler):
 
 
 def run_binary(cmd):
-    """\
-Run a binary
-Return output if good, None if bad
-"""
+    """\ Run a binary Return output if good, None if bad."""
 
     try:
         # sadly subprocess.check_output() is not in Python 2.6
@@ -72,7 +70,7 @@ Return output if good, None if bad
 
 
 class CpuTemp:
-    "Sensors on the CPU Core"
+    """Sensors on the CPU Core."""
     has_sensors = False
 
     def __init__(self):
@@ -85,7 +83,7 @@ class CpuTemp:
         self._pattern = re.compile('^\s+temp\d+_input:\s+([\d\.]+).*$')
 
     def get_data(self):
-        "Collects the data and return the output as an array"
+        """Collects the data and return the output as an array."""
         if not self.has_sensors:
             return None
 
@@ -113,7 +111,7 @@ class CpuTemp:
 
 
 class SmartCtl:
-    "Sensor on the Hard Drive"
+    """Sensor on the Hard Drive."""
     _drives = []
     has_smartctl = False
 
@@ -129,7 +127,7 @@ class SmartCtl:
             self._drives = sorted(self._drives)
 
     def get_data(self):
-        "Collects the data and return the output as an array"
+        """Collects the data and return the output as an array."""
         if not self.has_smartctl:
             return None
 
@@ -150,13 +148,12 @@ class SmartCtl:
 
 
 class Temper:
-    """\
-    Reads 'temper-poll -c' for room temperature data.
+    """\ Reads 'temper-poll -c' for room temperature data.
 
     Before you can use this class you must have a TEMPer USB thermometer
-    plugged in, and the temper-python package must be installed and configured.
-    See their documentation for that procedure.
-"""
+    plugged in, and the temper-python package must be installed and
+    configured. See their documentation for that procedure.
+    """
     has_temper = False
 
     def __init__(self):
@@ -166,7 +163,7 @@ class Temper:
             self.has_temper = True
 
     def get_data(self):
-        "Collects the data and return the output as an array"
+        """Collects the data and return the output as an array."""
         if not self.has_temper:
             return None
 
@@ -194,7 +191,7 @@ class Temper:
 
 
 class ZoneTemp:
-    "Zone sensors"
+    """Zone sensors."""
 
     def __init__(self):
         base_dir = '/sys/class/thermal/thermal_zone?/'
@@ -203,7 +200,7 @@ class ZoneTemp:
             self.zones.append(child)
 
     def get_data(self):
-        "Collects the data and return the output as an array"
+        """Collects the data and return the output as an array."""
         _zone = 0
         _data = []
         for zone in self.zones:
@@ -249,7 +246,7 @@ args = parser.parse_args()
 
 
 def logging_setup():
-    "Create logging object"
+    """Create logging object."""
     logFormat = logging.Formatter('%(message)s')
     # Create logger for cpuTemp
     tempLogger = logging.getLogger()
@@ -275,14 +272,14 @@ def logging_setup():
 
 
 def logData(log, data):
-    "log the data"
+    """log the data."""
     if data is not None:
         for _item in data:
             log.info(_item)
 
 
 def log_data():
-    "Write all temperature readings to one file"
+    """Write all temperature readings to one file."""
     # Create objects
     cpu = CpuTemp()
     zone = ZoneTemp()


=====================================
ntpclients/ntpmon.py
=====================================
@@ -2,8 +2,7 @@
 # -*- coding: utf-8 -*-
 
 # SPDX-License-Identifier: BSD-2-Clause
-'''\
-Any keystroke causes a poll and update. Keystroke commands:
+"""\ Any keystroke causes a poll and update. Keystroke commands:
 
 'a': Change peer display to apeers mode, showing association IDs.
 'd': Toggle detail mode (some peer will be reverse-video highlighted when on).
@@ -23,7 +22,7 @@ Any keystroke causes a poll and update. Keystroke commands:
 '+': Increase debugging level.  Output goes to ntpmon.log
 '-': Decrease debugging level.
 '?': Display helpscreen.
-'''
+"""
 
 from __future__ import print_function, division
 
@@ -71,38 +70,38 @@ stdscr = None
 
 
 def iso8601(t):
-    "ISO8601 string from Unix time."
+    """ISO8601 string from Unix time."""
     return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
 
 
-def statline(_peerlist, _mrulist, nyquist):
-    "Generate a status line"
+def statline(_peerlist, _mrulist, nyquist2):
+    """Generate a status line."""
     # We don't use stdversion here because the presence of a date is confusing
     leader = sysvars['version'][0]
     leader = re.sub(r" \([^\)]*\)", "", leader)
     if span.entries:
         trailer = "Updated: %s (%s)" \
                   % (iso8601(int(ntp.ntpc.lfptofloat(span.entries[0].last))),
-                     ntp.util.PeerSummary.prettyinterval(nyquist))
+                     ntp.util.PeerSummary.prettyinterval(nyquist2))
     else:
         trailer = ""
     spacer = ((peer_report.termwidth - 1) - len(leader) - len(trailer)) * " "
     return leader + spacer + trailer
 
 
-def peer_detail(variables, showunits=False):
-    "Show the things a peer summary doesn't, cooked slightly differently"
+def peer_detail(variables2, show_units=False):
+    """Show the things a peer summary doesn't, cooked slightly differently."""
     # All of an rv display except refid, reach, delay, offset, jitter.
     # One of the goals here is to emit field values at fixed positions
     # on the 2D display, so that changes in the details are easier to spot.
     vcopy = {}
     vcopyraw = {}
-    vcopy.update(variables)
+    vcopy.update(variables2)
     width = ntp.util.termsize().width - 2
     # Need to separate the casted from the raw
-    for key in vcopy.keys():
-        vcopyraw[key] = vcopy[key][1]
-        vcopy[key] = vcopy[key][0]
+    for ikey in vcopy:
+        vcopyraw[ikey] = vcopy[ikey][1]
+        vcopy[ikey] = vcopy[ikey][0]
     vcopy["leap"] = ("no-leap", "add-leap", "del-leap",
                      "unsync")[vcopy["leap"]]
     for fld in ('xmt', 'rec', 'reftime'):
@@ -110,7 +109,7 @@ def peer_detail(variables, showunits=False):
             vcopy[fld] = "***missing***"
         else:
             vcopy[fld] = ntp.util.rfc3339(ntp.ntpc.lfptofloat(vcopy[fld]))
-    if showunits:
+    if show_units:
         for name in ntp.util.MS_VARS:
             if name in vcopy:
                 vcopy[name] = ntp.util.unitify(vcopyraw[name],
@@ -155,12 +154,12 @@ filtdelay  = %(filtdelay)s
 filtoffset = %(filtoffset)s
 filtdisp   = %(filtdisp)s
 """
-    str = peerfmt % vcopy
-    return str.expandtabs()
+    out = peerfmt % vcopy
+    return out.expandtabs()
 
 
 class Fatal(Exception):
-    "Unrecoverable error."
+    """Unrecoverable error."""
 
     def __init__(self, msg):
         Exception.__init__(self)
@@ -172,7 +171,7 @@ class Fatal(Exception):
 
 class OutputContext:
     def __enter__(self):
-        "Begin critical region."
+        """Begin critical region."""
         if sys.version_info[0] < 3 and not disableunicode:
             # This appears to only be needed under python 2, it is only
             # activated when we already have UTF-8. Otherwise we drop
@@ -392,7 +391,7 @@ if __name__ == '__main__':
                                 strconvert = ntp.util.cook(clockvars,
                                                            showunits, " ")
                                 stdscr.addstr(strconvert.encode('UTF-8'))
-                            except ntp.packet.ControlException as e:
+                            except ntp.packet.ControlException:
                                 pass
                         elif span.entries:
                             strconvert = ntp.util.MRUSummary.header + "\n"
@@ -410,9 +409,9 @@ if __name__ == '__main__':
                 try:
                     helpmode = False
                     key = stdscr.getkey()
-                    if key == 'q' or key == 'x':
+                    if key in ('q', 'x'):
                         raise SystemExit(0)
-                    elif key == 'a':
+                    if key == 'a':
                         peer_report.displaymode = 'apeers'
                     elif key == 'd':
                         if not selectmode:
@@ -454,11 +453,12 @@ if __name__ == '__main__':
                             peer_report.displaymode = 'opeers'
                         else:
                             peer_report.displaymode = 'peers'
-                    elif key == 'j' or key == "KEY_DOWN":
+
+                    elif key in ('j', "KEY_DOWN"):
                         if showpeers:
                             selected += 1
                             selected %= len(peers)
-                    elif key == 'k' or key == "KEY_UP":
+                    elif key in ('k', "KEY_UP"):
                         if showpeers:
                             selected += len(peers) - 1
                             selected %= len(peers)


=====================================
ntpclients/ntpq.py
=====================================
@@ -56,7 +56,7 @@ NTP_FLOAT = 0xa   # Float value
 
 
 class Ntpq(cmd.Cmd):
-    "ntpq command interpreter"
+    """ntpq command interpreter."""
 
     def __init__(self, session):
         cmd.Cmd.__init__(self)
@@ -91,7 +91,7 @@ class Ntpq(cmd.Cmd):
                 for x in dir(self.__class__)]
 
     def emptyline(self):
-        "Called when an empty line is entered in response to the prompt."
+        """Called when an empty line is entered in response to the prompt."""
         pass
 
     def precmd(self, line):
@@ -102,7 +102,8 @@ class Ntpq(cmd.Cmd):
         return line
 
     def default(self, line):
-        "Called on an input line when the command prefix is not recognized."
+        """Called on an input line when the command prefix is not
+        recognized."""
         cmd, arg, line = self.parseline(line)
         try:
             dotext = 'do_'+cmd
@@ -264,7 +265,7 @@ usage: help [ command ]
             pass
 
     def __assoc_valid(self, line, required=False):
-        "Process a numeric associd or index."
+        """Process a numeric associd or index."""
         # FIXME: This does a useless call to __dogetassoc() when associd == 0
         # No big deal most of the time.  Just a useless packet exchange.
         if not line:
@@ -303,7 +304,7 @@ usage: help [ command ]
                 return associd
 
     def __assoc_range_valid(self, line):
-        "Try to get a range of assoc IDs."
+        """Try to get a range of assoc IDs."""
         tokens = line.split()
         if len(tokens) < 2:
             return ()
@@ -316,7 +317,7 @@ usage: help [ command ]
         return range(lo, hi+1)
 
     def printvars(self, variables, dtype, quiet):
-        "Dump variables in raw (actually, semi-cooked) mode."
+        """Dump variables in raw (actually, semi-cooked) mode."""
         if self.rawmode:
             if not quiet:
                 self.say("status=0x%04x,\n" % self.session.rstatus)
@@ -337,7 +338,7 @@ usage: help [ command ]
         self.say(text)
 
     def __dolist(self, varlist, associd, op, type, quiet=False):
-        "List variables associated with a specified peer."
+        """List variables associated with a specified peer."""
         try:
             variables = self.session.readvar(associd, varlist, op, raw=True)
         except ntp.packet.ControlException as e:
@@ -365,7 +366,7 @@ usage: help [ command ]
     # Unexposed helper tables and functions end here
 
     def do_units(self, _unused):
-        "toggle unit display"
+        """toggle unit display."""
         self.showunits = not self.showunits
 
     def help_units(self):
@@ -375,12 +376,12 @@ usage: units
 """)
 
     def do_EOF(self, _unused):
-        "exit ntpq"
+        """exit ntpq."""
         self.say("\n")
         return True
 
     def do_timeout(self, line):
-        "set the primary receive time out"
+        """set the primary receive time out."""
         if line:
             try:
                 self.session.primary_timeout = int(line)
@@ -395,7 +396,7 @@ usage: timeout [ msec ]
 """)
 
     def collect_display(self, associd, variables, decodestatus):
-        "Query and display a collection of variables from the system."
+        """Query and display a collection of variables from the system."""
         try:
             queried = self.session.readvar(associd,
                                            [v[0] for v in variables],
@@ -480,7 +481,7 @@ usage: timeout [ msec ]
             self.warn("display interrupted")
 
     def do_delay(self, line):
-        "set the delay added to encryption time stamps"
+        """set the delay added to encryption time stamps."""
         if not line:
             self.say("delay %d ms\n" % self.auth_delay)
         else:
@@ -498,7 +499,7 @@ usage: delay [ msec ]
 """)
 
     def do_host(self, line):
-        "specify the host whose NTP server we talk to"
+        """specify the host whose NTP server we talk to."""
         if not line:
             if self.session.havehost():
                 self.say("current host is %s\n" % self.session.hostname)
@@ -532,7 +533,7 @@ usage: host [-4|-6] [hostname]
 """)
 
     def do_poll(self, line):
-        "poll an NTP server in client mode `n' times"
+        """poll an NTP server in client mode `n' times."""
         # And it's not in the C version, so we're off the hook here
         self.warn("WARNING: poll not implemented yet")
 
@@ -543,7 +544,7 @@ usage: poll [n] [verbose]
 """)
 
     def do_passwd(self, line):
-        "specify a password to use for authenticated requests"
+        """specify a password to use for authenticated requests."""
         try:
             self.session.password()
         except ntp.packet.ControlException as e:
@@ -558,7 +559,7 @@ usage: passwd []
 """)
 
     def do_hostnames(self, line):
-        "specify whether hostnames or net numbers are printed"
+        """specify whether hostnames or net numbers are printed."""
         if not line:
             pass
         elif line == "yes":
@@ -588,7 +589,7 @@ usage: hostnames [yes|no|hostname|hostnum]
 """)
 
     def do_debug(self, line):
-        "set/change debugging level"
+        """set/change debugging level."""
         if not line:
             pass
         elif line == "more":
@@ -607,8 +608,10 @@ usage: hostnames [yes|no|hostname|hostnum]
         self.say("debug level is %d\n" % self.debug)
 
     def do_logfile(self, line):
-        """view/change logfile. \"<stderr>\" will log to stderr
-           instead of a file"""
+        """view/change logfile.
+
+        \"<stderr>\" will log to stderr instead of a file
+        """
         if not line:
             self.say(repr(self.logfp.name) + "\n")
             return
@@ -631,7 +634,7 @@ usage: debug [no|more|less|n]
 """)
 
     def do_exit(self, line):
-        "exit ntpq"
+        """exit ntpq."""
         return True
 
     def help_exit(self):
@@ -648,7 +651,7 @@ usage: quit
 """)
 
     def do_keyid(self, line):
-        "set keyid to use for authenticated requests"
+        """set keyid to use for authenticated requests."""
         if line:
             try:
                 self.session.keyid = int(line)
@@ -666,7 +669,7 @@ usage: keyid [key#]
 """)
 
     def do_version(self, line):
-        "print version number"
+        """print version number."""
         self.say(version + "\n")
 
     def help_version(self):
@@ -676,7 +679,7 @@ usage: version
 """)
 
     def do_direct(self, line):
-        "toggle direct mode output"
+        """toggle direct mode output."""
         self.directmode = not self.directmode
         if self.directmode:
             self.say("Direct mode is on\n")
@@ -690,7 +693,7 @@ usage: direct
 """)
 
     def do_raw(self, line):
-        "do raw mode variable output"
+        """do raw mode variable output."""
         self.rawmode = True
         self.say("Output set to raw\n")
 
@@ -701,7 +704,7 @@ usage: raw
 """)
 
     def do_cooked(self, line):
-        "do cooked mode variable output"
+        """do cooked mode variable output."""
         self.rawmode = False
         self.say("Output set to cooked\n")
 
@@ -712,7 +715,7 @@ usage: cooked
 """)
 
     def do_authenticate(self, line):
-        "always authenticate requests to this server"
+        """always authenticate requests to this server."""
         if not line:
             pass
         elif line == "yes":
@@ -733,7 +736,7 @@ usage: authenticate [yes|no]
 """)
 
     def do_ntpversion(self, line):
-        "set the NTP version number to use for requests"
+        """set the NTP version number to use for requests."""
         if not line:
             pass
         else:
@@ -757,7 +760,7 @@ usage: ntpversion [version number]
 """)
 
     def do_keytype(self, line):
-        "set key type to use for authenticated requests"
+        """set key type to use for authenticated requests."""
         if not line:
             self.say("Keytype: %s\n" % self.session.keytype)
         elif line.upper() in ['AES', 'AES128CMAC']:
@@ -775,7 +778,8 @@ usage: keytype [digest-name]
 """)
 
     def do_associations(self, line):
-        "print list of association IDs and statuses for the server's peers"
+        """print list of association IDs and statuses for the server's
+        peers."""
         if self.__dogetassoc():
             self.__printassoc(showall=True)
 
@@ -786,7 +790,7 @@ usage: associations
 """)
 
     def do_passociations(self, line):
-        "print list of associations returned by last associations command"
+        """print list of associations returned by last associations command."""
         self.__printassoc(showall=True)
 
     def help_passociations(self):
@@ -796,7 +800,7 @@ usage: passociations
 """)
 
     def do_lassociations(self, line):
-        "print list of associations including all client information"
+        """print list of associations including all client information."""
         if self.__dogetassoc():
             self.__printassoc(showall=True)
 
@@ -807,9 +811,8 @@ usage: lassociations
 """)
 
     def do_lpassociations(self, line):
-        """\
-print last obtained list of associations, including client information
-"""
+        """\ print last obtained list of associations, including client
+        information."""
         self.__printassoc(showall=True)
 
     def help_lpassociations(self):
@@ -820,7 +823,7 @@ usage: lpassociations
 """)
 
     def do_addvars(self, line):
-        "add variables to the variable list or change their values"
+        """add variables to the variable list or change their values."""
         if not line:
             self.warn("usage: addvars name[=value][,...]\n")
             return
@@ -839,7 +842,7 @@ usage: addvars name[=value][,...]
 """)
 
     def do_rmvars(self, line):
-        "remove variables from the variable list"
+        """remove variables from the variable list."""
         if not line:
             self.warn("usage: rmvars name[,...]\n")
             return
@@ -857,7 +860,7 @@ usage: rmvars name[,...]
 """)
 
     def do_clearvars(self, line):
-        "remove all variables from the variable list"
+        """remove all variables from the variable list."""
         self.uservars.clear()
 
     def help_clearvars(self):
@@ -867,7 +870,7 @@ usage: clearvars
 """)
 
     def do_showvars(self, line):
-        "print variables on the variable list"
+        """print variables on the variable list."""
         if not self.uservars:
             self.say("No variables on list.\n")
         for (name, value) in self.uservars.items():
@@ -883,7 +886,7 @@ usage: showvars
 """)
 
     def do_readlist(self, line):
-        "read the system or peer variables included in the variable list"
+        """read the system or peer variables included in the variable list."""
         associd = self.__assoc_valid(line)
         if associd >= 0:
             qtype = ntp.ntpc.TYPE_SYS if associd == 0 else ntp.ntpc.TYPE_PEER
@@ -897,7 +900,7 @@ usage: readlist [assocID]
 """)
 
     def do_rl(self, line):
-        "read the system or peer variables included in the variable list"
+        """read the system or peer variables included in the variable list."""
         self.do_readlist(line)
 
     def help_rl(self):
@@ -907,7 +910,7 @@ usage: rl [assocID]
 """)
 
     def do_writelist(self, line):
-        "write the system or peer variables included in the variable list"
+        """write the system or peer variables included in the variable list."""
         pass
 
     def help_writelist(self):
@@ -917,7 +920,7 @@ usage: writelist [ assocID ]
 """)
 
     def do_readvar(self, line):
-        "read system or peer variables"
+        """read system or peer variables."""
         associd = self.__assoc_valid(line)
         if associd >= 0:
             qtype = ntp.ntpc.TYPE_SYS if associd == 0 else ntp.ntpc.TYPE_PEER
@@ -931,7 +934,7 @@ usage: readvar [assocID] [varname1] [varname2] [varname3]
 """)
 
     def do_rv(self, line):
-        "read system or peer variables"
+        """read system or peer variables."""
         self.do_readvar(line)
 
     def help_rv(self):
@@ -941,7 +944,7 @@ usage: rv [assocID] [varname1] [varname2] [varname3]
 """)
 
     def do_writevar(self, line):
-        "write system or peer variables"
+        """write system or peer variables."""
         pass
 
     def help_writevar(self):
@@ -951,7 +954,7 @@ usage: writevar assocID name=value,[...]
 """)
 
     def do_mreadlist(self, line):
-        "read the peer variables in the variable list for multiple peers"
+        """read the peer variables in the variable list for multiple peers."""
         if not line:
             self.warn("usage: mreadlist assocIDlow assocIDhigh\n")
             return
@@ -973,7 +976,7 @@ usage: mreadlist assocIDlow assocIDhigh
 """)
 
     def do_mrl(self, line):
-        "read the peer variables in the variable list for multiple peers"
+        """read the peer variables in the variable list for multiple peers."""
         if not line:
             self.warn("usage: mrl assocIDlow assocIDhigh")
             return
@@ -986,7 +989,7 @@ usage: mrl assocIDlow assocIDhigh
 """)
 
     def do_mreadvar(self, line):
-        "read peer variables from multiple peers"
+        """read peer variables from multiple peers."""
         if not line:
             self.warn("usage: mreadvar assocIDlow assocIDhigh  "
                       "[ name=value[,...] ]")
@@ -1010,7 +1013,7 @@ usage: mreadvar assocIDlow assocIDhigh [name=value[,...]]
 """)
 
     def do_mrv(self, line):
-        "read peer variables from multiple peers"
+        """read peer variables from multiple peers."""
         if not line:
             self.warn(
                 "usage: mrv assocIDlow assocIDhigh [name=value[,...]]")
@@ -1024,7 +1027,7 @@ usage: mrv assocIDlow assocIDhigh [name=value[,...]]
 """)
 
     def do_clocklist(self, line):
-        "read the clock variables included in the variable list"
+        """read the clock variables included in the variable list."""
         assoc = self.__assoc_valid(line)
         if assoc >= 0:
             self.__dolist(self.uservars.keys(),
@@ -1038,7 +1041,7 @@ usage: clocklist [assocID]
 """)
 
     def do_cl(self, line):
-        "read the clock variables included in the variable list"
+        """read the clock variables included in the variable list."""
         self.do_clocklist(line)
 
     def help_cl(self):
@@ -1048,7 +1051,7 @@ usage: cl [assocID]
 """)
 
     def do_clockvar(self, line):
-        "read clock variables"
+        """read clock variables."""
         assoc = self.__assoc_valid(line)
         if assoc == 0:
             self.warn("This command requires the association ID of a clock.")
@@ -1063,7 +1066,7 @@ usage: clockvar [assocID] [name=value[,...]]
 """)
 
     def do_cv(self, line):
-        "read clock variables"
+        """read clock variables."""
         self.do_clockvar(line)
 
     def help_cv(self):
@@ -1073,7 +1076,7 @@ usage: cv [ assocID ] [ name=value[,...] ]
 """)
 
     def do_pstats(self, line):
-        "show statistics for a peer"
+        """show statistics for a peer."""
         pstats = (
             ("srcadr", "remote host:          ", NTP_ADD),
             ("dstadr", "local address:        ", NTP_ADD),
@@ -1105,7 +1108,7 @@ usage: pstats assocID
 """)
 
     def do_peers(self, line):
-        "obtain and print a list of the server's peers [IP version]"
+        """obtain and print a list of the server's peers [IP version]"""
         self.__dopeers(showall=True, mode="peers")
 
     def help_peers(self):
@@ -1115,9 +1118,8 @@ usage: peers
 """)
 
     def do_apeers(self, line):
-        """
-obtain and print a list of the server's peers and their assocIDs [IP version]
-"""
+        """obtain and print a list of the server's peers and their assocIDs [IP
+        version]"""
         self.__dopeers(showall=True, mode="apeers")
 
     def help_apeers(self):
@@ -1128,7 +1130,7 @@ usage: apeers
 """)
 
     def do_lpeers(self, line):
-        "obtain and print a list of all peers and clients [IP version]"
+        """obtain and print a list of all peers and clients [IP version]"""
         self.__dopeers(showall=True, mode="peers")
 
     def help_lpeers(self):
@@ -1138,9 +1140,8 @@ usage: lpeers
 """)
 
     def do_opeers(self, line):
-        """
-print peer list the old way, with dstadr shown rather than refid [IP version]
-"""
+        """print peer list the old way, with dstadr shown rather than refid [IP
+        version]"""
         self.__dopeers(showall=True, mode="opeers")
 
     def help_opeers(self):
@@ -1151,8 +1152,8 @@ usage: opeers
 """)
 
     def do_lopeers(self, line):
-        """obtain and print a list of all peers and clients showing
-        dstadr [IP version]"""
+        """obtain and print a list of all peers and clients showing dstadr [IP
+        version]"""
         self.__dopeers(showall=True, mode="opeers")
 
     def help_lopeers(self):
@@ -1163,7 +1164,7 @@ usage: lopeers
 """)
 
     def do_hot_config(self, line):
-        "send a remote configuration command to ntpd"
+        """send a remote configuration command to ntpd."""
         try:
             self.session.password()
         except ntp.packet.ControlException as e:
@@ -1198,7 +1199,7 @@ usage: config <configuration command line>
 """)
 
     def do_config_from_file(self, line):
-        "configure ntpd using the configuration filename"
+        """configure ntpd using the configuration filename."""
         try:
             with open(line) as rfp:
                 self.say("%s\n" % self.session.config(rfp.read()))
@@ -1229,9 +1230,9 @@ usage: noflake
     def do_doflake(self, line):
         """Drop some received packets for testing.
 
-        Probabilities 0 and 1 should be certainly accepted
-        and discarded respectively. No default, but 0.1
-        should be a one in ten loss rate.
+        Probabilities 0 and 1 should be certainly accepted and discarded
+        respectively. No default, but 0.1 should be a one in ten loss
+        rate.
         """
         try:
             _ = float(line)
@@ -1252,8 +1253,11 @@ usage: doflake <probability>
 """)
 
     def do_mrulist(self, line):
-        """display the list of most recently seen source addresses,
-           tags mincount=... resall=0x... resany=0x..."""
+        """display the list of most recently seen source addresses, tags
+        mincount=...
+
+        resall=0x... resany=0x...
+        """
         cmdvars = {}
         for item in line.split(" "):
             if not item:
@@ -1278,9 +1282,9 @@ usage: doflake <probability>
             self.say("Ctrl-C will stop MRU retrieval and display "
                      "partial results.\n")
         if self.rawmode:
-            mruhook = lambda v: self.printvars(variables=v,
-                                               dtype=ntp.ntpc.TYPE_SYS,
-                                               quiet=True)
+            def mruhook(v): return self.printvars(variables=v,
+                                                  dtype=ntp.ntpc.TYPE_SYS,
+                                                  quiet=True)
         else:
             mruhook = None
         try:
@@ -1340,7 +1344,7 @@ usage: mrulist [tag=value] [tag=value] [tag=value] [tag=value]
 """)
 
     def do_ifstats(self, line):
-        "show statistics for each local address ntpd is using"
+        """show statistics for each local address ntpd is using."""
         try:
             self.session.password()
             entries = self.session.ifstats()
@@ -1365,7 +1369,7 @@ usage: ifstats
 """)
 
     def do_reslist(self, line):
-        "show ntpd access control list"
+        """show ntpd access control list."""
         try:
             self.session.password()
             entries = self.session.reslist()
@@ -1392,7 +1396,7 @@ usage: reslist
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_sysinfo(self, _line):
-        "display system summary"
+        """display system summary."""
         sysinfo = (
             ("peeradr", "system peer:      ", NTP_ADP),
             ("peermode", "system peer mode: ", NTP_MODE),
@@ -1420,7 +1424,7 @@ usage: sysinfo
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_kerninfo(self, _line):
-        "display kernel loop and PPS statistics"
+        """display kernel loop and PPS statistics."""
         kerninfo = (
             ("koffset", "pll offset:          ", NTP_FLOAT),
             ("kfreq", "pll frequency:       ", NTP_FLOAT),
@@ -1450,7 +1454,7 @@ usage: kerninfo
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_sysstats(self, _line):
-        "display system uptime and packet counts"
+        """display system uptime and packet counts."""
         sysstats = (
             ("ss_uptime", "uptime:               ", NTP_INT),
             ("ss_reset", "sysstats reset:       ", NTP_INT),
@@ -1477,7 +1481,7 @@ usage: sysstats
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_monstats(self, _line):
-        "display monitor (mrulist) counters and limits"
+        """display monitor (mrulist) counters and limits."""
         monstats = (
             ("mru_enabled",     "enabled:              ", NTP_INT),
             ("mru_hashslots",   "hash slots in use:    ", NTP_INT),
@@ -1507,7 +1511,7 @@ usage: monstats
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_authinfo(self, _line):
-        "display symmetric authentication counters"
+        """display symmetric authentication counters."""
         authinfo = (
             ("authreset",          "time since reset:    ", NTP_INT),
             ("authkeys",           "stored keys:         ", NTP_INT),
@@ -1538,24 +1542,24 @@ usage: authinfo
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_ntsinfo(self, _line):
-        "display NTS authentication counters"
+        """display NTS authentication counters."""
         ntsinfo = (
-   ("nts_client_send",           "NTS client sends:          ", NTP_INT),
-   ("nts_client_recv_good",      "NTS client recvs good:     ", NTP_INT),
-   ("nts_client_recv_bad",       "NTS client recvs w error:  ", NTP_INT),
-   ("nts_server_recv_good",      "NTS server recvs good:     ", NTP_INT),
-   ("nts_server_recv_bad",       "NTS server recvs w error:  ", NTP_INT),
-   ("nts_server_send",           "NTS server sends:          ", NTP_INT),
-   ("nts_cookie_make",           "NTS make cookies:          ", NTP_INT),
-   ("nts_cookie_decode",         "NTS decode cookies:        ", NTP_INT),
-   ("nts_cookie_decode_old",     "NTS decode cookies old:    ", NTP_INT),
-   ("nts_cookie_decode_too_old", "NTS decode cookies too old:", NTP_INT),
-   ("nts_cookie_decode_error",   "NTS decode cookies error:  ", NTP_INT),
-   ("nts_ke_probes_good",        "NTS KE probes good:        ", NTP_INT),
-   ("nts_ke_probes_bad",         "NTS KE probes_bad:         ", NTP_INT),
-   ("nts_ke_serves_good",        "NTS KE serves good:        ", NTP_INT),
-   ("nts_ke_serves_bad",         "NTS KE serves_bad:         ", NTP_INT),
-  )
+            ("nts_client_send",           "NTS client sends:          ", NTP_INT),
+            ("nts_client_recv_good",      "NTS client recvs good:     ", NTP_INT),
+            ("nts_client_recv_bad",       "NTS client recvs w error:  ", NTP_INT),
+            ("nts_server_recv_good",      "NTS server recvs good:     ", NTP_INT),
+            ("nts_server_recv_bad",       "NTS server recvs w error:  ", NTP_INT),
+            ("nts_server_send",           "NTS server sends:          ", NTP_INT),
+            ("nts_cookie_make",           "NTS make cookies:          ", NTP_INT),
+            ("nts_cookie_decode",         "NTS decode cookies:        ", NTP_INT),
+            ("nts_cookie_decode_old",     "NTS decode cookies old:    ", NTP_INT),
+            ("nts_cookie_decode_too_old", "NTS decode cookies too old:", NTP_INT),
+            ("nts_cookie_decode_error",   "NTS decode cookies error:  ", NTP_INT),
+            ("nts_ke_probes_good",        "NTS KE probes good:        ", NTP_INT),
+            ("nts_ke_probes_bad",         "NTS KE probes_bad:         ", NTP_INT),
+            ("nts_ke_serves_good",        "NTS KE serves good:        ", NTP_INT),
+            ("nts_ke_serves_bad",         "NTS KE serves_bad:         ", NTP_INT),
+        )
         self.collect_display(associd=0, variables=ntsinfo, decodestatus=False)
 
     def help_ntsinfo(self):
@@ -1567,8 +1571,10 @@ usage: ntsinfo
 
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
+
+
     def do_iostats(self, _line):
-        "display network input and output counters"
+        """display network input and output counters."""
         iostats = (
             ("iostats_reset", "time since reset:     ", NTP_INT),
             ("total_rbuf", "receive buffers:      ", NTP_INT),
@@ -1594,7 +1600,7 @@ usage: iostats
 # FIXME: This table should move to ntpd
 #          so the answers track when ntpd is updated
     def do_timerstats(self, line):
-        "display interval timer counters"
+        """display interval timer counters."""
         timerstats = (
             ("timerstats_reset", "time since reset:  ", NTP_INT),
             ("timer_overruns", "timer overruns:    ", NTP_INT),


=====================================
ntpclients/ntpsnmpd.py
=====================================
@@ -43,7 +43,7 @@ DEFLOG = "ntpsnmpd.log"
 
 
 class DataSource(ntp.agentx.MIBControl):
-    def __init__(self, hostname=DEFHOST, settingsFile=None, notifySpin=0.1):
+    def __init__(self, ihostname=DEFHOST, settingsFile=None, notifySpin=0.1):
         # This is defined as a dict tree because it is simpler, and avoids
         # certain edge cases
         # OIDs are relative from ntp root
@@ -152,7 +152,7 @@ class DataSource(ntp.agentx.MIBControl):
         # print(repr(self.oidTree))
         # print(self.oidTree[1]["subids"][1][1][0])
         self.session = ntp.packet.ControlSession()
-        self.hostname = hostname if hostname else DEFHOST
+        self.hostname = ihostname if ihostname else DEFHOST
         self.session.openhost(self.hostname)
         self.settingsFilename = settingsFile
         # Cache so we don't hammer ntpd, default 1 second timeout
@@ -356,8 +356,8 @@ class DataSource(ntp.agentx.MIBControl):
         if data is None:
             return None
         protoerr = 0
-        for key in data.keys():
-            protoerr += data[key]
+        for ikey in data.keys():
+            protoerr += data[ikey]
         return ax.Varbind(ax.VALUE_COUNTER32, oid, protoerr)
 
     def cbr_statusNotifications(self, oid):
@@ -537,7 +537,7 @@ class DataSource(ntp.agentx.MIBControl):
             try:
                 sockinfo = socket.getaddrinfo(srcadr, None)[0][-1]
                 addr = sockinfo[0]
-                ipv6 = True if len(sockinfo) == 4 else False
+                ipv6 = bool(len(sockinfo) == 4)
             except socket.gaierror:
                 addr = None  # how to handle?
                 ipv6 = None
@@ -615,8 +615,8 @@ class DataSource(ntp.agentx.MIBControl):
             if pvars is None:
                 return None
             protoerr = 0
-            for key in pvars.keys():
-                protoerr += pvars[key]
+            for ikey in pvars.keys():
+                protoerr += pvars[ikey]
             return ax.Varbind(ax.VALUE_COUNTER32, oid, protoerr)
         return self.dynamicCallbackSkeleton(handler)
 
@@ -663,7 +663,7 @@ class DataSource(ntp.agentx.MIBControl):
         if oldMode is None:
             self.oldValues["mode"] = newMode
             return
-        elif oldMode != newMode:
+        if oldMode != newMode:
             self.oldValues["mode"] = newMode
             vl = [ax.Varbind(ax.VALUE_OID, snmpTrapOID,
                              ax.OID(ntpRootOID + (0, 1))),


=====================================
ntpclients/ntpsweep.py
=====================================
@@ -40,12 +40,12 @@ except ImportError as e:
     sys.exit(1)
 
 
-def ntp_peers(host):
+def ntp_peers(server):
     """Return: a list of peer IP addrs for a specified host,
             empty list if query failed.
     """
     try:
-        with os.popen("ntpq -npw " + host) as rp:
+        with os.popen("ntpq -npw " + server) as rp:
             hostlines = rp.readlines()[2:]      # Drop display header
             # Strip tally mark from first field
             return [ln.split()[0][1:] for
@@ -118,7 +118,7 @@ def scan_host(host, level):
             printhost = printhost.replace(strip, "")
         # append number of peers in brackets if requested and valid
         if (recurse and (known_host_info[host] != " ?") and
-           (host in known_host_peers)):
+                (host in known_host_peers)):
             printhost += " (%d)" % len(known_host_peers[host])
         # Finally print complete host line
         print("%-32s %s" % (printhost[:32], known_host_info[host]))
@@ -139,7 +139,7 @@ def scan_host(host, level):
                     # Might cause problems in the future.  First
                     # part of the guard is an attempt to skip
                     # NTPsec-style clock IDs.
-                    if peer[0].isdigit() and not peer.startswith("127"):
+                    if peer[0].isdigit() and not peer.startswith("127.127."):
                         scan_host(peer, level + 1)
     else:   # We did not get answers from this host
         printhost = (' ' * level) + (ntp.util.canonicalize_dns(host) or host)
@@ -166,21 +166,21 @@ if __name__ == '__main__':
     recurse = False
     strip = ""
     for (switch, val) in options:
-        if switch == "-h" or switch == "--host":
+        if switch in ("-h", "--host"):
             hostlist = [val]
-        elif switch == "-l" or switch == "--host-list":
+        elif switch in ("-l", "--host-list"):
             hostlist = val.split(",")
-        elif switch == "-m" or switch == "--maxlevel":
+        elif switch in ("-m", "--maxlevel"):
             errmsg = "Error: -m parameter '%s' not a number\n"
             maxlevel = ntp.util.safeargcast(val, int, errmsg, __doc__)
-        elif switch == "-p" or switch == "--peers":
+        elif switch in ("-p", "--peers"):
             recurse = True
-        elif switch == "-s" or switch == "--strip":
+        elif switch in ("-s", "--strip"):
             strip = val
-        elif switch == "-?" or switch == "--help":
+        elif switch in ("-?", "--help"):
             print(__doc__, file=sys.stderr)
             raise SystemExit(0)
-        elif switch == "-V" or switch == "--version":
+        elif switch in ("-V", "--version"):
             print("ntpsweep %s" % ntp.util.stdversion())
             raise SystemExit(0)
 


=====================================
ntpclients/ntptrace.py
=====================================
@@ -29,32 +29,29 @@ except ImportError as e:
 
 
 def get_info(host):
-    info = ntp_read_vars(0, [], host)
-    if info is None or 'stratum' not in info:
-        return
+    info3 = ntp_read_vars(0, [], host)
+    if info3 is None or 'stratum' not in info3:
+        return None
 
-    info['offset'] = round(float(info['offset']) / 1000, 6)
-    info['syncdistance'] = \
-        (float(info['rootdisp']) + (float(info['rootdelay']) / 2)) / 1000
+    info3['offset'] = round(float(info3['offset']) / 1000, 6)
+    info3['syncdistance'] = \
+        (float(info3['rootdisp']) + (float(info3['rootdelay']) / 2)) / 1000
 
-    return info
+    return info3
 
 
 def get_next_host(peer, host):
-    info = ntp_read_vars(peer, ["srcadr"], host)
-    if info is None:
-        return
-    return info['srcadr']
+    info2 = ntp_read_vars(peer, ["srcadr"], host)
+    if info2 is None:
+        return None
+    return info2['srcadr']
 
 
 def ntp_read_vars(peer, vars, host):
     obsolete = {'phase': 'offset',
                 'rootdispersion': 'rootdisp'}
 
-    if not vars:
-        do_all = True
-    else:
-        do_all = False
+    do_all = bool(not vars)
     outvars = {}.fromkeys(vars)
 
     if do_all:
@@ -95,8 +92,7 @@ def ntp_read_vars(peer, vars, host):
             key = match.group(1)
             val = match.group(2)
             val = re.sub(r'^"([^"]+)"$', r'\1', val)
-            if key in obsolete:
-                key = obsolete[key]
+            key = dict.get(obsolete, key, key)
             if do_all or key in outvars:
                 outvars[key] = val
 
@@ -134,18 +130,18 @@ numeric = False
 maxhosts = 99
 host = '127.0.0.1'
 
-for (switch, val) in options:
-    if switch == "-m" or switch == "--max-hosts":
+for (switch, value) in options:
+    if switch in ("-m", "--max-hosts"):
         errmsg = "Error: -m parameter '%s' not a number\n"
-        maxhosts = ntp.util.safeargcast(val, int, errmsg, usage)
-    elif switch == "-n" or switch == "--numeric":
+        maxhosts = ntp.util.safeargcast(value, int, errmsg, usage)
+    elif switch in ("-n", "--numeric"):
         numeric = True
-    elif switch == "-r" or switch == "--host":
-        host = val
-    elif switch == "-?" or switch == "--help" or switch == "--more-help":
+    elif switch in ("-r", "--host"):
+        host = value
+    elif switch in ("-?", "--help", "--more-help"):
         print(usage, file=sys.stderr)
         raise SystemExit(0)
-    elif switch == "-V" or switch == "--version":
+    elif switch in ("-V", "--version"):
         print("ntptrace %s" % ntp.util.stdversion())
         raise SystemExit(0)
 


=====================================
ntpclients/ntpviz.py
=====================================
@@ -69,9 +69,9 @@ if sys.version_info[0] == 2:
     sys.setdefaultencoding('utf8')
 
     def open(file, mode='r', buffering=-1, encoding=None, errors=None):
-        "Redefine open()"
+        """Redefine open()"""
         return(codecs.open(filename=file, mode=mode, encoding=encoding,
-               errors=errors, buffering=buffering))
+                           errors=errors, buffering=buffering))
 
 # believe it or not, Python has no way to make a simple constant!
 MS_PER_S = 1e3          # milliseconds per second
@@ -103,7 +103,7 @@ refclock_name = {'127.127.20.0': 'NMEA(0)',
 # Gack, python before 3.2 has no defined tzinfo for utc...
 # define our own
 class UTC(datetime.tzinfo):
-    """UTC"""
+    """UTC."""
 
     def utcoffset(self, dt):
         return datetime.timedelta(0)
@@ -132,10 +132,10 @@ if (3 > sys.version_info[0]) and (7 > sys.version_info[1]):
 
 # overload ArgumentParser
 class MyArgumentParser(argparse.ArgumentParser):
-    "class to parse arguments"
+    """class to parse arguments."""
 
     def convert_arg_line_to_args(self, arg_line):
-        '''Make options file more tolerant'''
+        """Make options file more tolerant."""
         # strip out trailing comments
         arg_line = re.sub('\s+#.*$', '', arg_line)
 
@@ -150,7 +150,7 @@ class MyArgumentParser(argparse.ArgumentParser):
 
 
 def print_profile():
-    """called by atexit() on normal exit to print profile data"""
+    """called by atexit() on normal exit to print profile data."""
     pr.disable()
     pr.print_stats('tottime')
     pr.print_stats('cumtime')
@@ -164,7 +164,7 @@ def print_profile():
 #   Mean, Variance, Standard Deviation, Skewness and Kurtosis
 
 class RunningStats(object):
-    "Calculate mean, variance, sigma, skewness and kurtosis"
+    """Calculate mean, variance, sigma, skewness and kurtosis."""
 
     def __init__(self, values):
         self.num = len(values)     # number of samples
@@ -202,7 +202,7 @@ class RunningStats(object):
 
 # class for calced values
 class VizStats(ntp.statfiles.NTPStats):
-    "Class for calculated values"
+    """Class for calculated values."""
 
     percs = {}          # dictionary of percentages
     title = ''          # title
@@ -373,7 +373,7 @@ class VizStats(ntp.statfiles.NTPStats):
 
 
 def gnuplot_fmt(min_val, max_val):
-    "return optimal gnuplot format"
+    """return optimal gnuplot format."""
     span = max_val - min_val
     if 6 <= span:
         fmt = '%.0f'
@@ -392,7 +392,7 @@ def gnuplot_fmt(min_val, max_val):
 # Investigate.
 
 def gnuplot(template, outfile=None):
-    "Run a specified gnuplot program."
+    """Run a specified gnuplot program."""
 
     if not template:
         # silently ignore empty plots
@@ -444,7 +444,7 @@ def gnuplot(template, outfile=None):
 
 
 class NTPViz(ntp.statfiles.NTPStats):
-    "Class for visualizing statistics from a single server."
+    """Class for visualizing statistics from a single server."""
 
     # Python takes single quotes here. Since no % substitution
     Common = """\
@@ -468,7 +468,7 @@ set rmargin 10
                                         endtime=endtime)
 
     def plot_slice(self, rows, item1, item2=None):
-        "slice 0,item1, maybe item2, from rows, ready for gnuplot"
+        """slice 0,item1, maybe item2, from rows, ready for gnuplot."""
         # speed up by only sending gnuplot the data it will actually use
         # WARNING: this is hot code, only modify if you profile
         # since we are looping the data, get the values too
@@ -515,7 +515,7 @@ set rmargin 10
         return (plot_data, values1)
 
     def local_offset_gnuplot(self):
-        "Generate gnuplot code graphing local clock loop statistics"
+        """Generate gnuplot code graphing local clock loop statistics."""
         if not self.loopstats:
             sys.stderr.write("ntpviz: WARNING: no loopstats to graph\n")
             return ''
@@ -578,7 +578,7 @@ file.</p>
         return ret
 
     def local_freq_temps_plot(self):
-        "Generate gnuplot code graphing local frequency and temps"
+        """Generate gnuplot code graphing local frequency and temps."""
         if not self.loopstats:
             sys.stderr.write("ntpviz: WARNING: no loopstats to graph\n")
             return ''
@@ -671,7 +671,7 @@ file, and field 3 from the tempstats log file.</p>
         return ret
 
     def local_temps_gnuplot(self):
-        "Generate gnuplot code graphing local temperature statistics"
+        """Generate gnuplot code graphing local temperature statistics."""
         sitename = self.sitename
         tempsmap = self.tempssplit()
         tempslist = list(tempsmap.keys())
@@ -733,7 +733,7 @@ component of frequency drift.</p>
         return ret
 
     def local_gps_gnuplot(self):
-        "Generate gnuplot code graphing local GPS statistics"
+        """Generate gnuplot code graphing local GPS statistics."""
         sitename = self.sitename
         gpsmap = self.gpssplit()
         gpslist = list(gpsmap.keys())
@@ -793,7 +793,7 @@ plot \\
             plot_template += """\
 '-' using 1:2 title '%s TDOP' with line ls 1, \\
 '-' using 1:3 title '%s nSat' with line ls 2 axis x1y2, \\
-""" % (key,)
+""" % (key, key)
 
         # strip the trailing ", \\n"
         plot_template = plot_template[:-4] + "\n"
@@ -816,7 +816,7 @@ impossible.</p>
         return ret
 
     def local_error_gnuplot(self):
-        "Plot the local clock frequency error."
+        """Plot the local clock frequency error."""
         if not self.loopstats:
             sys.stderr.write("ntpviz: WARNING: no loopstats to graph\n")
             return ''
@@ -875,7 +875,7 @@ line at 0ppm.  Expected values of 99%-1% percentiles: 0.4ppm</p>
         return ret
 
     def loopstats_gnuplot(self, fld, title, legend, freq):
-        "Generate gnuplot code of a given loopstats field"
+        """Generate gnuplot code of a given loopstats field."""
         if not self.loopstats:
             sys.stderr.write("ntpviz: WARNING: no loopstats to graph\n")
             return ''
@@ -943,16 +943,16 @@ plot \
         return ret
 
     def local_offset_jitter_gnuplot(self):
-        "Generate gnuplot code of local clock loop standard deviation"
+        """Generate gnuplot code of local clock loop standard deviation."""
         return self.loopstats_gnuplot(4, "Local RMS Time Jitter", "Jitter", 0)
 
     def local_offset_stability_gnuplot(self):
-        "Generate gnuplot code graphing local clock stability"
+        """Generate gnuplot code graphing local clock stability."""
         return self.loopstats_gnuplot(5, "Local RMS Frequency Jitter",
                                       "Stability", 1)
 
     def peerstats_gnuplot(self, peerlist, fld, title, ptype):
-        "Plot a specified field from peerstats."
+        """Plot a specified field from peerstats."""
 
         peerdict = self.peersplit()
         if not peerlist:
@@ -1167,17 +1167,17 @@ plot \
         return ret
 
     def peer_offsets_gnuplot(self, peerlist=None):
-        "gnuplot Peer Offsets"
+        """gnuplot Peer Offsets."""
         return self.peerstats_gnuplot(peerlist, 4, "Server Offset",
                                       "offset")
 
     def peer_jitters_gnuplot(self, peerlist=None):
-        "gnuplot Peer Jitters"
+        """gnuplot Peer Jitters."""
         return self.peerstats_gnuplot(peerlist, 7, "Server Jitter",
                                       "jitter")
 
     def local_offset_histogram_gnuplot(self):
-        "Plot a histogram of clock offset values from loopstats."
+        """Plot a histogram of clock offset values from loopstats."""
         if not self.loopstats:
             sys.stderr.write("ntpviz: WARNING: no loopstats to graph\n")
             return ''
@@ -1286,7 +1286,7 @@ plot \
 
 
 def local_offset_multiplot(statlist):
-    "Plot comparative local offsets for a list of NTPViz objects."
+    """Plot comparative local offsets for a list of NTPViz objects."""
 
     out = {}
     out['size'] = args.img_size
@@ -1295,7 +1295,7 @@ def local_offset_multiplot(statlist):
     plot = NTPViz.Common + '''\
 set terminal %(terminal)s size %(size)s
 set title "Multiplot Local Clock Offsets"
-set ytics format "%1.2f μs" nomirror textcolor rgb "#0060ad"
+set ytics format "%%1.2f μs" nomirror textcolor rgb "#0060ad"
 set key bottom right box
 plot \\
 ''' % out
@@ -1546,7 +1546,7 @@ Python by ESR, concept and gnuplot code by Dan Drown.
                 'pngcairo': '.png',
                 'png': '.png',
                 'svg': '.svg',
-               }
+                }
     if args.terminal in term_map:
         args.img_ext = term_map[args.terminal]
     else:
@@ -1987,7 +1987,7 @@ ntpviz</a>, part of the <a href="https://www.ntpsec.org/">NTPsec project</a>
                 index_buffer += "<div>\n%s</div>\n" % image['html']
             index_buffer += "<br><br>\n"
             gnuplot(image['plot'], os.path.join(args.outdir,
-                    imagename + args.img_ext))
+                                                imagename + args.img_ext))
             index_buffer += "</div>\n"
 
     # dump stats


=====================================
ntpclients/ntpwait.py
=====================================
@@ -24,8 +24,8 @@ signal.signal(signal.SIGINT, lambda signal, frame: sys.exit(2))
 
 import getopt
 import re
-import time
 import socket
+import time
 
 try:
     import ntp.magic


=====================================
tests/option-tester.sh
=====================================
@@ -19,7 +19,7 @@ PURGE=""
 SECCOMP="$(pkg-config libseccomp --variable=includedir)"
 SECCOMP="$SECCOMP/seccomp.h"
 LINUX=""
-if [ `uname -s` = "Linux" -a -n "$SECCOMP" -a -f "$SECCOMPH" ]
+if [ "$(uname -s)" = "Linux" -a -n "$SECCOMP" -a -f "$SECCOMPH" ]
 then
   # Not supported on CentOS 6
   LINUX="--enable-seccomp"
@@ -38,7 +38,7 @@ then
     DISABLE_NTS="--disable-nts"
   fi
 else
-  if ! $PYTHON ../wafhelpers/tlscheck
+  if ! "${PYTHON}" ../wafhelpers/tlscheck
   then
     DISABLE_NTS="--disable-nts"
   fi
@@ -46,22 +46,22 @@ fi
 
 doit ()
 {
-  DIR=test-$1
-  [ ! -d $DIR ] && mkdir $DIR
-  rm -rf $DIR/*
-  $PYTHON ./waf configure $DISABLE_NTS --out=$DIR $2 2>&1 | tee    $DIR/test.log
+  DIR="test-${1}"
+  [ ! -d "${DIR}" ] && mkdir "${DIR}"
+  rm -rf "${DIR}/"*
+  "${PYTHON}" ./waf configure "${DISABLE_NTS}" --out="${DIR}" $2 2>&1 | tee    "${DIR}/test.log"
   WAF1=$?
   WAF2=0
   WAF3=0
   if [ "$WAF1" = 0 ]
   then
-  echo                                 2>&1    | tee -a $DIR/test.log
-  $PYTHON ./waf build                   2>&1    | tee -a $DIR/test.log
+  echo                                 2>&1    | tee -a "${DIR}/test.log"
+  "${PYTHON}" ./waf build                   2>&1    | tee -a "${DIR}/test.log"
   WAF2=$?
   if [ "$WAF2" = 0 ]
   then
-  echo                                 2>&1    | tee -a $DIR/test.log
-  $PYTHON ./waf check                   2>&1    | tee -a $DIR/test.log
+  echo                                 2>&1    | tee -a "${DIR}/test.log"
+  "${PYTHON}" ./waf check                   2>&1    | tee -a "${DIR}/test.log"
   WAF3=$?
   else
     PURGE="${PURGE} ${PYTHON}-${DIR}-build"
@@ -71,8 +71,8 @@ doit ()
   fi
   if [ "$WAF1" != 0 -o "$WAF2" != 0 -o "$WAF3" != 0 ]
   then
-    echo                               2>&1   | tee -a $DIR/test.log
-    echo "Trouble with $DIR"           2>&1   | tee -a $DIR/test.log
+    echo                                 2>&1   | tee -a "${DIR}/test.log"
+    echo "Trouble with ${DIR}"           2>&1   | tee -a "${DIR}/test.log"
   fi
   if [ "$WAF3" != 0 ]
   then
@@ -91,8 +91,8 @@ doit classic "--enable-classic-mode --refclock=all --disable-doc --disable-manpa
 
 doit all     "--enable-warnings --enable-debug --enable-debug-gdb --enable-debug-timing --refclock=all --enable-leap-smear --enable-mssntp --enable-early-droproot --disable-fuzz $LINUX --disable-doc --disable-manpage"
 
-if [ "`which asciidoc 2>/dev/null`" != "" -a \
-     "`which xsltproc 2>/dev/null`" != "" ]
+if [ "$(which asciidoc 2>/dev/null)" != "" -a \
+     "$(which xsltproc 2>/dev/null)" != "" ]
 then
 doit doc     ""
 fi
@@ -107,10 +107,10 @@ grep "The configuration failed"  test*/test.log
 grep ^Trouble                    test*/test.log
 echo
 
-echo -n "## ";  $PYTHON --version
-if test -n "$PYTHONPATH"
+echo -n "## ";  "${PYTHON}" --version
+if test -n "${PYTHONPATH}"
 then
-  echo "## PYTHONPATH is" \"$PYTHONPATH\"
+  echo "## PYTHONPATH is \"${PYTHONPATH}\""
 fi
 
 if ! (set -o pipefail) 2>/dev/null
@@ -121,7 +121,7 @@ then
   PURGE="${PURGE} pipefail"
 fi
 
-if [ `uname -s` = "Linux" -a -z "$SECCOMP" ]
+if [ $(uname -s) = "Linux" -a -z "$SECCOMP" ]
 then
     echo
     echo "### Warning: Missing seccomp.h (on a Linux system)"


=====================================
tests/python2-tester.sh
=====================================
@@ -5,7 +5,7 @@
 # This is a clone of option-tester.sh
 # to build with python2 and do minimal (version) testing.
 
-if [ "`which python2 2>/dev/null`" = "" ]
+if [ "$(which python2 2>/dev/null)" = "" ]
 then
   echo "# Error: No python2 on this system."
   exit 1
@@ -21,28 +21,28 @@ fi
 doit ()
 {
   DIR=test-$1
-  [ ! -d $DIR ] && mkdir $DIR
-  rm -rf $DIR/*
-  python2 ./waf configure --out=$DIR $2 2>&1 | tee    $DIR/test.log
+  [ ! -d "${DIR}" ] && mkdir "${DIR}"
+  rm -rf "${DIR}"/*
+  python2 ./waf configure --out="${DIR}" $2 2>&1 | tee    "${DIR}/test.log"
   WAF1=$?
   WAF2=0
   WAF3=0
   if [ "$WAF1" = 0 ]
   then
-  echo                            2>&1   | tee -a $DIR/test.log
-  python2 ./waf build             2>&1   | tee -a $DIR/test.log
+  echo                            2>&1   | tee -a "${DIR}/test.log"
+  python2 ./waf build             2>&1   | tee -a "${DIR}/test.log"
   WAF2=$?
   if [ "$WAF2" = 0 ]
   then
-  echo                            2>&1   | tee -a $DIR/test.log
-  python2 ./waf check             2>&1   | tee -a $DIR/test.log
+  echo                            2>&1   | tee -a "${DIR}/test.log"
+  python2 ./waf check             2>&1   | tee -a "${DIR}/test.log"
   WAF3=$?
   fi
   fi
   if [ "$WAF1" != 0 -o "$WAF2" != 0 -o "$WAF3" != 0 ] 
   then
-    echo                          2>&1   | tee -a $DIR/test.log
-    echo "Trouble with $DIR"      2>&1   | tee -a $DIR/test.log
+    echo                          2>&1   | tee -a "${DIR}/test.log"
+    echo "Trouble with ${DIR}"      2>&1   | tee -a "${DIR}/test.log"
   fi
   echo
   echo
@@ -61,9 +61,9 @@ grep ^Trouble                    test*/test.log
 echo
 
 echo -n "## ";  python2 --version
-if test -n "$PYTHONPATH"
+if test -n "${PYTHONPATH}"
 then
-  echo "## PYTHONPATH is" \"$PYTHONPATH\"
+  echo "## PYTHONPATH is \"${PYTHONPATH}\""
 fi
 
 if ! /bin/sh -c "set -o pipefail" 2> /dev/null


=====================================
tests/python3-tester.sh
=====================================
@@ -5,7 +5,7 @@
 # This is a clone of option-tester.sh
 # to build with python3 and do minimal (version) testing.
 
-if [ "`which python3 2>/dev/null`" = "" ]
+if [ "$(which python3 2>/dev/null)" = "" ]
 then
   echo "# Error: No python3 on this system."
   exit 1
@@ -21,28 +21,28 @@ fi
 doit ()
 {
   DIR=test-$1
-  [ ! -d $DIR ] && mkdir $DIR
-  rm -rf $DIR/*
-  python3 ./waf configure --out=$DIR $2 2>&1 | tee    $DIR/test.log
+  [ ! -d "${DIR}" ] && mkdir "${DIR}"
+  rm -rf "${DIR}"/*
+  python3 ./waf configure --out="${DIR}" $2 2>&1 | tee    "${DIR}/test.log"
   WAF1=$?
   WAF2=0
   WAF3=0
   if [ "$WAF1" = 0 ]
   then
-  echo                            2>&1   | tee -a $DIR/test.log
-  python3 ./waf build             2>&1   | tee -a $DIR/test.log
+  echo                            2>&1   | tee -a "${DIR}/test.log"
+  python3 ./waf build             2>&1   | tee -a "${DIR}/test.log"
   WAF2=$?
   if [ "$WAF2" = 0 ]
   then
-  echo                            2>&1   | tee -a $DIR/test.log
-  python3 ./waf check             2>&1   | tee -a $DIR/test.log
+  echo                            2>&1   | tee -a "${DIR}/test.log"
+  python3 ./waf check             2>&1   | tee -a "${DIR}/test.log"
   WAF3=$?
   fi
   fi
   if [ "$WAF1" != 0 -o "$WAF2" != 0 -o "$WAF3" != 0 ] 
   then
-    echo                          2>&1   | tee -a $DIR/test.log
-    echo "Trouble with $DIR"      2>&1   | tee -a $DIR/test.log
+    echo                          2>&1   | tee -a "${DIR}/test.log"
+    echo "Trouble with ${DIR}"      2>&1   | tee -a "${DIR}/test.log"
   fi
   echo
   echo
@@ -61,9 +61,9 @@ grep ^Trouble                    test*/test.log
 echo
 
 echo -n "## ";  python3 --version
-if test -n "$PYTHONPATH"
+if test -n "${PYTHONPATH}"
 then
-  echo "## PYTHONPATH is" \"$PYTHONPATH\"
+  echo "## PYTHONPATH is \"${PYTHONPATH}\""
 fi
 
 if ! /bin/sh -c "set -o pipefail" 2> /dev/null



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/-/compare/3bcd808bd5daf1db2559a412276a35d5ea605001...a447e1f7ac5d7310628c2b7b36ea4758804f2334

-- 
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/-/compare/3bcd808bd5daf1db2559a412276a35d5ea605001...a447e1f7ac5d7310628c2b7b36ea4758804f2334
You're receiving this email because of your account on gitlab.com.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20201120/dda07b06/attachment-0001.htm>


More information about the vc mailing list